Css height in percent not working
When setting CSS height in percent, it's crucial to make sure the element's immediate parent has a fixed height. This is because the percentage is computed relative to the parent's height, thus without a defined height for the parent, the percentage value will float aimlessly like a lost pong ball:
Notice how we give a height to our .parent
character? With that, their .child
understands how big 50% should be.
For those aiming to achieve full viewport height, independent of parent sizes, here's a hot tip: use the vh
unit. Think of it as a rebel child who doesn't care about parent's rules:
And for designers juggling nested elements, use the flexbox or grid layout. They offer more control and autonomy than a hormonal teenager.
Parent-child relationships in CSS: Decoding the heights
When you size using percentage in CSS, it's like a game of hide and seek with the parent element. If the parent doesn't have a height set, the child's percentage height turns into a game of invisible hide and seek - it just doesn't work.
Building the CSS family home
This sets the stage for the following nested elements to play height percentages out correctly. Think of it as building a home for your CSS family.
Going rogue: using viewport units
Just as we have some free spirits amongst us who value personal space above family ties, viewport units like vh
, vw
, vmin
, and vmax
let your elements be.
Flexing control with Flexbox and Grid
With Flexbox and Grid, you can tell elements to fill up the available space, giving them more room and you more control. It's modern architecture for modern CSS homes.
Resolving the sneaky and unexpected
Padding and margin ninjas
Resetting default padding and margins is like having pest control on speed dial, it stops layout bugs in their tracks.
The style tugs-of-war a.k.a. conflicting styles
Conflicting styles can sometimes override your height settings in an arm-wrestling contest. Low blow, I know. Identifying them is a critical step in tackling this issue.
'vh' units: The modern trend
The vh
units are the hipsters of modern browsers and have been around since IE9+. Although, you can't ignore some attention-seeking mobile browsers that demand special treatment with svh
, lvh
, dvh
units.
JavaScript: The knight in shining armor
When CSS throws a tantrum, you can always count on JavaScript to keep things running smoothly:
Was this article helpful?