为什么位置:绝对;会扩大测试div的高度吗?

时间:2017-06-23 13:03:59

标签: html css

div.test被设置为自动高度,没有固定高度。

.test {
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  background: yellow;
  width: 200px;
  height: auto;
  padding: 10px;
}
<div class="test">
  it is a test info for my div .
</div>

现在要在css中添加position:absolute;,其他所有css属性都保持不变。

.test {
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  background: yellow;
  width: 200px;
  height: auto;
  padding: 10px;
  position: absolute;
}
<div class="test">
  it is a test info for my div .
</div>

div.test的高度被放大了,为什么?

2 个答案:

答案 0 :(得分:6)

在第一种情况下,div的positionstatic,因此top / right / bottom / left属性不适用。将位置更改为absolute后,现在会考虑这些属性。特别是bottom属性导致div扩展。尝试从代码中删除bottom: 0;,然后您就会看到div崩溃回到内容的高度:

&#13;
&#13;
.test { 
    top: 0;
    right: 0;
    left: 0;
    background: yellow;
    width: 200px;
    height: auto;
    padding: 10px;
    position: absolute;
}
&#13;
<div class="test">it is a test info for my div.</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

尝试使用max-height:以确保它不会超出您的预期。

相关问题