当我将 left:x 添加到标签时,为什么我的标签会超过 div-width?
.TheDiv {
background-color: orange;
height: 100px;
width: 200px;
}
.TheLabel {
background-color: green;
position: relative;
left: 30px;
}
<div class="TheDiv">
<label class="TheLabel">See this label is going past the div</label><br>
<label class="TheLabel">See this label is going past the div</label>
</div>
最佳答案
因为 child 仍然在使用 parent 的宽度,因为您没有正确使用绝对定位。父级应该有 position: relative
child 应该有position: absolute
为此工作。
这是应用此代码后的代码:
.TheDiv {
background-color: orange;
height: 50px;
width: 200px;
position: relative; /* Added this*/
}
.TheLabel {
background-color: green;
position: absolute; /* Changed this*/
left: 30px;
}
<div class="TheDiv">
<label class="TheLabel">See this label is going past the div</label>
</div>
如果您想保留
position: relative
让它们自动堆叠在一起,然后将它们显示为 block
s 并限制他们的 width
,像这样:.TheDiv {
background-color: orange;
height: 100px;
width: 200px;
}
.TheLabel {
background-color: green;
position: relative;
left: 30px;
/* Add this part */
display: block;
width: 170px; /* parent's width - child's left*/
margin-bottom: 2px; /* instead of <br> */
}
<div class="TheDiv">
<label class="TheLabel">See this label is going past the div</label>
<label class="TheLabel">See this label is going past the div</label>
</div>
关于左侧的 HTML/CSS 标签越过 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48899029/