我遇到了一个问题。
如何使一个 div 扩展至定位元素的末尾。
.apple {
background: #ccc;
width: auto;
}
<div class="apple">
A for aplle
<br><a style="position:relative; top:20px;">B for Ball</a>
</div>
这里,div元素不接受位置改变元素的宽度。如何让它起作用。谢谢。
它正在执行其应该做的事情。您将元素定位于自然下降DOM的下方20px处,因此它被放置在灰色div外部。我了解您的情况可能更加复杂。您是否可以添加padding-bottom:20px
之类的内容?
.apple {
background: #ccc;
width: auto;
padding-bottom: 20px;
}
<div class="apple">
A for aplle
<br><a style="position:relative; top:20px;">B for Ball</a>
</div>
display: table;
,并在子元素中添加display: table-row;
。
.apple {
background: #ccc;
width: auto;
display: table;
}
.apple a {
display: table-row;
}
<div class="apple">
A for aplle
<br><a style="position:relative; top:20px;">B for Ball</a>
</div>
position: relative
会将元素从其原始位置移开(如果有top、bottom、right或left设置),但仍保留它原来的空间,即在其原始(未移动)位置上看到的空间。与static
定位相比,它不会改变父元素的尺寸。
为了解决这个问题,您可以将a
标签设置为inline-block
,删除相对定位并使用margin-top
代替top
。这将被父元素包裹:
.apple {
background: #ccc;
width: auto;
}
<div class="apple">
A for aplle
<br><a style="display: inline-block; margin-top:20px;">B for Ball</a>
</div>
margin
或padding
替代top
位置。 - DaniP