html - 将绝对定位的 DIV *完全* 放在相对定位的父 DIV 中?

标签 html css

我想使用 CSS(而不是 JavaScript)将具有 position:absolute EXACTLY 的子 DIV 放入其 position:relative 父级中。这正是问题所在。

如下图所示,子 DIV 非常适合父 DIV 的左/右和上边距,但超出父 DIV 的下边距(看起来是)1px

Illustration of parent and child DIVs

关键是我已经为子 DIV 尝试了各种 HEIGHT 组合。这种方法并没有真正解决问题,因为调整页面大小会移动子 DIV 相对于其父级的下边距。所以我不认为解决方法是更改​​ HEIGHT 的值。

这是 CSS:

div.container{
  position: relative;
  background-color: #fafafa;
  margin: 2%;
  border: solid 2px orange;
  padding: 2%;
  height: 100%; /* Expands container to height of HTML & BODY */
}

div.leftSideNav,
div.rightSideNav
{
  height: 100%; /* Changing height doesn't seem to truly fix the problem */
  width: 1.5%;
  background-color: #ccffcc;
  margin: 0px;
  border: solid 1px #33bb88;
  padding: 0px;
  position: absolute;
  top: 0px;
  color: #333333;
}

div.leftSideNav{
  left: 0px;
  background-color: pink;
}
div.rightSideNav{
  right: 0px;
}

这是相应的 XHMTL:

<body>
  <div class="container">
   <div class="leftSideNav" />
   <div class="rightSideNav" />
  </div>
</body>

我一直在兜圈子进行实验,并试图让子 DIV 的底部边距适合它们的父级 ala 上/左/右边距。我发现了很多一般性讨论,但没有一个专门讨论如何在父 DIV 中获取子 DIV 的底部边距。

最佳答案

绝对定位的 child 周围有一个 1px 的边框:

border: solid 1px #33bb88;

这就是溢出的根源。

height:100% + 1px + 1px = 2px overflow

您可以使用 CSS calc() 函数使元素精确匹配:

height: calc(100% - 2px);

调整CSS Box Model在宽度/高度计算中包括填充和边框。默认值为 box-sizing: content-box。试试 box-sizing: border-box 代替。

div.leftSideNav,
div.rightSideNav
{
  height: calc(100% - 2px);    /* OPTION #1 */
  box-sizing: border-box;      /* OPTION #2 */
  width: 1.5%;
  background-color: #ccffcc;
  margin: 0px;
  border: solid 1px #33bb88;
  padding: 0px;
  position: absolute;
  top: 0px;
  color: #333333;

}

引用资料:

关于html - 将绝对定位的 DIV *完全* 放在相对定位的父 DIV 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37402214/

相关文章:

css - 为 child 覆盖 css flex align-content

html - 我有一个固定的菜单。我想创建一个按钮(在菜单中),从它的位置升起固定菜单

html - 如何对首屏内容使用内联 CSS

html - 与打印 View 和浏览器 View 相比有很大差异

javascript - JQuery - 只需走进主要的 li 元素

javascript - 在javascript中显示缩略图中的大图片

css - Ext JS 4.2 - 如何创建类似于 KitchenSink 示例中的 header ?

python - Xpath 在第一个 html 标记后获取文本

html - 更改发发心的边框颜色

javascript - 如何根据歌曲的频率调整图片比例?