0

For the given CSS below, why is child more than 10px as I've specified 100%. Also shouldn't child start from left:0 and top:0. Why is it starting from left:20px and top: 20px ?

My understanding about absolute position is that, it's position and sizing will be relative to a parent that's positioned. Here parent is static. Therefore it fallbacks to root i.e., body for sizing and positioning. Why does the child respects padding of parent ?

body {
  border: 0.1em solid;
  height: 10px;
}

.parent {
  padding: 20px;
}

.child {
  position: absolute;
  border: 0.1rem solid;
  height: 100%;
}
<div class="parent">
  <div class="child"></div>
</div>
j08691
  • 204,283
  • 31
  • 260
  • 272
akhildevelops
  • 159
  • 1
  • 8
  • 1
    It's not respecting the padding. Since you didn't give the `child` element a `top` value, it's being placed in the next logical position in the DOM, which is outside of the `body` element. Use dev tools and you'll see how the `child` element is positioned. Set a `top: 0` value on the `child` and you'll see it positioned against the `parent`'s 0,0 coordinates – disinfor May 17 '23 at 14:56
  • 1
    `position: absolute` will only be relative to the parent if the parent forms a new containing block. See [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block) for details. – Adam May 17 '23 at 14:59
  • @Adam `parent` has `position: relative` set, so it is a containing block, the issue is more the `position: absolute` element - with no `top`, `bottom`, `left` or `right` values. [MDN position](https://developer.mozilla.org/en-US/docs/Web/CSS/position) – disinfor May 17 '23 at 15:02
  • 1
    I don't see any `position: relative` in the CSS in the question??? – Adam May 17 '23 at 15:06
  • 1
    @Adam you are absolutely correct! My brain must have made it up. So, OP, read up on the MDN article that Adam links to. – disinfor May 17 '23 at 15:14
  • 1
    I thought I was losing my mind too haha. Have a great day @disinfor – Adam May 17 '23 at 15:42

0 Answers0