Alvaro
Alvaro

Reputation: 9662

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.

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>

Upvotes: 1

Views: 2853

Answers (3)

Stickers
Stickers

Reputation: 78686

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

Upvotes: 0

haltersweb
haltersweb

Reputation: 3139

This is because an absolutely positioned element is taken out of it's parent's flow.

It therefore no longer recognizes the padding of the parent.

It simply relates itself to the boundary of whatever ancestor has a position relative or position absolute. The boundary's 0,0 point is the point just inside the border and stretches horizontally to the right boundary just before any right-hand border.

You will therefore have to define similar padding to the absolutely positioned element that you did on its parent.

Upvotes: 1

johnchinjew
johnchinjew

Reputation: 150

A possible solution: Add a width property to the #children on hover.

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

Upvotes: 0

Related Questions