Say I have this HTML
<div id="outer">
<div id="inner">
<div id="nested">
</div>
</div>
</div>
Where
- all the DIVs are responsive, in that #outer’s width is a percentage of the window width
- #inner is "always" smaller than #outer
With CSS, is there a way to set the width of #nested so that it’s a percentage of the width of #outer?
2
Answers
You can do so with
position: relative
andposition: absolute
Both these attributes go hand-in-hand as the
absolute
element is positioned relative to its closest parent/ancestor. It goes up to thebody
tag if none are found. By settingposition: relative
onouter
, you make it the closest ancestor, so the width ofnested
adjusts in relation to that.Take advantages of the CSS FlexBox Layout and the flex property and all of its great features. You can read more about flex on this link. Check my example below using the flex value in the display property. Happy Coding!