左侧的 HTML/CSS 标签越过 div

标签 html css

当我将 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/

相关文章:

javascript - 对特定的 PHP 函数进行 jQuery AJAX 调用

javascript - 如何防止关闭的 </option> 标签被删除?

html - 带有绝对定位文本的图像

html - 将 img 大小(保持宽高比)自动缩放到父级的 div 高度

javascript - 如何在 html 中创建新的容器标签

javascript - 跟踪并显示用户在我的网站上点击按钮的次数

html - 在 Bootstrap 行中重复 html 的背景图像

asp.net - div float :left style within an asp TabContainer

javascript - OnClick 第一次不起作用

css - css 中用于多个 ID 的数组