Maintaining Aspect Ratio in Auto-Resizing Div Elements
Problem Statement
Create a div element that:
Solution
Utilizing the aspect-ratio property, you can achieve the desired behavior:
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: /* this gradient is a proof that the ratio is maintained since the angle is fixed */ linear-gradient(30deg,red 50%,transparent 50%), chocolate; }
Explanation
width: Calculates the width based on the smaller of:
This solution allows you to create a div that automatically resizes, maintaining its original aspect ratio, within the specified maximum dimensions.
The above is the detailed content of How to Maintain Aspect Ratio in Auto-Resizing Divs?. For more information, please follow other related articles on the PHP Chinese website!