相对位置和绝对位置之间的填充

Padding between relative and absolute positions

我正在将子元素的定位从相对更改为绝对。

子元素的宽度是父元素宽度的百分比。当我将位置从相对位置更改为绝对位置时,百分比现在包括父级的填充。在演示中将黑色悬停 div.

JSFiddle.

body {
  margin: 0;
}

#parent {
  width: calc(100% - 100px);
  height: 100vh;
  padding-right: 100px;
  background: pink;
  position: relative;
}

.children {
  position: relative;
  width: 50%;
  height: 100%;
  background: black;
  float: left;
}
.children:nth-child(2) {
  background: grey;
}

#parent:hover .children {
  position: absolute;
  top: 0;
  left: 0;
}
#parent:hover .children:nth-child(2) {
  left: 50%;
}
<div id="parent">

  <div class="children"></div>
  <div class="children"></div>

</div>

可能的解决方案:在悬停时为#children 添加宽度 属性。

#children:hover {
    width: calc(100% - 100px) /* <-- Add this */
    position: absolute;
    top: 0;
    left: 0;
}

当一个元素设置为position:absolute时,它的包含框是父元素的padding box(padding周围的框)。您示例中的结果是正确的。

jsFiddle

您可能会这样做以获得您想要的结果,并且在您的示例中似乎没有必要在父级上 width:calc(100% - 100px)

#children:hover {
  position: absolute;
  top: 0;
  left: 0;
  right: 100px; /* the same value as parent's right padding */
  width: auto; /* reset to default, depending on 'left' and 'right' values */
}

编辑

OP其实里面有两个绝对div,使用calc()可以帮助。

jsFiddle

#parent:hover .children {
  position: absolute;
  top: 0;
  left: 0;
  width: calc(50% - 50px);
}
#parent:hover .children:nth-child(2) {
  left: calc(50% - 50px);
}

但是,最简单的方法 是向父级添加一个额外的容器,并在其上设置内边距和背景,其余样式不变。

jsFiddle

<div id="container">
  <div id="parent">
    <div class="children"></div>
    <div class="children"></div>
  </div>
</div>

#container {
  padding-right: 100px;
  background: pink;
}
#parent {
  height: 100vh;
  position: relative;
}

这是因为绝对定位元素从其父元素流中取出。

因此它不再识别父级的填充。

它只是将自己与任何具有相对位置或绝对位置的祖先的边界相关联。边界的 0,0 点是边界内的点,并水平延伸到右边界之前的任何右边界。

因此,您必须为绝对定位元素定义与其父元素类似的填充。