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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3