首页 > 解决方案 > 为什么父div和孩子的身高不一样?

问题描述

我有一个看起来像按钮的链接,我想将背景颜色设置为不同的。

但是,我不明白为什么我的holderdiv 没有和它的孩子一样高。我不考虑填充。

有没有一种干净的方法来解决这个问题?

.link {
  background-color: green;
  padding: .9rem 3rem;
}

.holder {
  background-color: red;
  text-align: center;
  margin-top: 40px;
}
<div class="holder">
  <a href="#" class="link">LINK</a>
</div>

标签: htmlcss

解决方案


You need to add display: inline-block to your .link element:

.link {
  background-color: green;
  padding: .9rem 3rem;
  display: inline-block;
}

.holder {
  background-color: red;
  text-align: center;
  margin-top: 40px;
}
<div class="holder">
  <a href="#" class="link">LINK</a>
</div>

By default, <a> elements are display: inline, and do not have their layout impacted by the containing block. That is to say, they do not allow for a height or width to be set, and do not respect vertical padding and margins.


推荐阅读