Jonah Jonah - 4 months ago 22
CSS Question

Bordered child div that exactly overlaps bordered parent div?

Assume for this solution that we do not know the parent div's dimensions.

A picture will illustrate the problem best:

Russian doll divs

The parent div has a black border, and the child div has a purple border of the same width. The child expands to fill the parent (as desired) but the expanstion does not include the borders (not desired). Instead, the child should fit exactly on top of the parent, like two stacked pieces of glass of exactly the same dimensions, so that parent is perfectly covered by the child.

Snippet that produces the picture above





html { box-sizing: border-box; }
*, *:before, *:after { box-sizing: inherit; }


.parent {
background: pink;
border: 3px solid black;
position: relative;
width: 100px;
height: 100px;
}

.child {
background: green;
border: 3px solid purple;
position: absolute;
width: 100%;
height: 100%;
left: 0;
top: 0;
}

<div class="parent">
<div class="child">
</div>
</div>





Snippet producing correct results, but illegal because parent divs dimensions are used





html { box-sizing: border-box; }
*, *:before, *:after { box-sizing: inherit; }


.parent {
background: pink;
border: 3px solid black;
position: relative;
width: 100px;
height: 100px;
}

.child {
background: green;
border: 3px solid purple;
position: absolute;
width: 100px; /* not allowed! should be 100% */
height: 100px;/* not allowed! should be 100% */
left: -3px;
top: -3px;
}

<div class="parent">
<div class="child">
</div>
</div>





Question



How can the effect of the 2nd snippet be produced without knowing the parent
div
s width and height? It's okay to use the parent
div
s border width, but the width and height properties of the child should both be
100%
.

Answer

Make the width and height of the child 'inherit'. This will inherit the width and height of the parent.

html { box-sizing: border-box; }
*, *:before, *:after { box-sizing: inherit; }


.parent {
  background: pink;
  border: 3px solid black;
  position: relative;
  width: 100px;
  height: 100px;
}

.child {
  background: green;
  border: 3px solid purple;
  position: absolute;
  width: inherit;
  height: inherit;
  left: -3px;
  top: -3px;
}
<div class="parent">
  <div class="child">
  </div>
</div>