Height equal to dynamic width (CSS fluid layout)
For dynamically setting a CSS element's height equal to its variable width, you utilize the padding-top
property. Set this property as a percentage to create a relative height in accordance with the width:
Translate this style into your HTML:
Your .square
class now maintains a 1:1 aspect ratio, akin to a well-behaved square adjusting with changing width.
Bootstrap of dynamic sizing: pseudo-elements
Pseudo-elements offer another layer of flexibility to maintain the aspect ratio of div with changing content. The ::before
or ::after
pseudo-elements act as invisible square drill sergeants, keeping the aspect ratio in check.
Blend this structure into your HTML:
Moving with the times: aspect-ratio
For those with a certain edge, aka modern browsers, make use of the shiny new aspect-ratio
property:
Viewport gymnastics with vw
/vh
In response to changing viewports, let vw
(viewport width) and vh
(viewport height) do the heavy lifting:
Your box now sticks to a 1:1 aspect ratio, pirouetting gracefully with viewport's ebbs and flows.
In-practice applications and considerations
Play with aspect ratios
Experiment with the padding-top
for different aspect ratios:
- For a 4:3 aspect ratio, like vintage TVs, use
padding-top: 75%
. - For a cinematic 16:9 aspect ratio, the golden
padding-top: 56.25%
stands ready.
Reacting to resizing with JavaScript
Don't let JavaScript or jQuery feel left out. Listen to window resize
events to keep the aspect ratio on its toes, and maintain your peace of mind.
Cross-browser consensus
Compatibility check, anyone? Remember to verify CSS aspect-ratio
on caniuse.com.
Tambourine over the pseudo-element
Absolute positioning
— keep your eye on the .content
. It fits just right, like Cinderella's slipper, on the space padded by the pseudo-element.
Must-try examples and tweaking experiments
Embed CodePen or JSFiddle sandboxes. Code tinkering is the coder's playground — adjust widths, maintain aspect ratios and get your hands dirty.
Was this article helpful?