Alvaro Alvaro - 8 days ago 6
CSS Question

Padding between relative and absolute positions

I am changing the positioning of children elements from relative to absolute.

The children elements have a width which is a percentage of the parent's width. When I change the position from relative to absolute, the percentage now includes the parent's padding. In the demo hover the black div.


  • How can I avoid the parent padding being included in the children's percentage?

  • Why does it act differently in both position values?



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>




Answer

When an element is set to position:absolute, its containing box is the parent's padding box (the box around the padding). The result in your example is correct.

jsFiddle

You can probably do this to get the result you want, and width:calc(100% - 100px) on the parent doesn't seem to be necessary in your example.

#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 */
}

EDIT

OP actually has two absolute divs inside, using calc() can help.

jsFiddle

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

But, the easiest way would be adding an additional container to the parent, and set the padding and background on it, rest of style unchanged.

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;
}