Maintaining Aspect Ratio in Auto-Resizing Div Elements
When creating a resizable div element that remains centered on the screen, it's important to ensure that its aspect ratio is maintained, regardless of changes in window size. This can be achieved using CSS techniques.
CSS Solution:
The aspect-ratio property provides a simple solution to maintain aspect ratio in resizing div elements. The following CSS code demonstrates how to achieve this:
body { height: 100vh; margin: 0; display: flex; justify-content: center; align-items: center; background: gray; } .stage { --r: 960 / 540; // Define the desired aspect ratio (width / height) aspect-ratio: var(--r); // Set the aspect ratio width:min(90%, min(960px, 90vh*(var(--r)))); // Set the maximum width and height while preserving ratio display: flex; justify-content: center; align-items: center; background: linear-gradient(30deg,red 50%,transparent 50%), // Add a gradient to visualize the preserved aspect ratio chocolate; }
Explanation:
The width property ensures that the element's width remains within the specified constraints:
Result:
The above CSS code results in a div element that remains centered on the screen, maintains its desired aspect ratio, and resizes to fit the available window space. This solution works effectively for resizing both the width and height of the element.
The above is the detailed content of How Can I Maintain Aspect Ratio in a Resizable, Centered Div Element?. For more information, please follow other related articles on the PHP Chinese website!