为什么当我向标签添加左边的x时,我的标签会越过div宽度?
.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>
&#13;
答案 0 :(得分:2)
因为您没有正确使用绝对定位,所以孩子仍然采用父母的宽度。父母应该position: relative
,孩子应该有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
并限制他们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>
答案 1 :(得分:0)
这是我为我的案例找到的最佳解决方案。添加display:block和width:x到标签。
.TheDiv {
background-color: orange;
height: 100px;
width: 200px;
}
.TheLabel {
background-color: green;
position: relative;
display: block;
width: 170px;
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>