Preserving Aspect Ratio in Auto-Resizing Div Elements
Div elements can be challenging to style when they need to fit varying screen sizes while maintaining a specific aspect ratio. This can be achieved using the aspect-ratio CSS property alongside an intuitive combination of width and height attributes.
To gracefully handle both width and height changes, you can leverage the aspect ratio calculation --r = width / height. Here's how to implement it in CSS:
body { height: 100vh; margin: 0; display: flex; justify-content: center; align-items: center; background: gray; } .stage { --r: 960 / 540; aspect-ratio: var(--r); width: min(90%, min(960px, 90vh * var(--r))); display: flex; justify-content: center; align-items: center; background: linear-gradient(30deg, red 50%, transparent 50%), chocolate; }
In this example:
Such an approach ensures that the div element automatically resizes while maintaining the desired aspect ratio, accommodating both width and height variations.
The above is the detailed content of How Can I Preserve Aspect Ratio in Auto-Resizing Div Elements Using CSS?. For more information, please follow other related articles on the PHP Chinese website!