Home > Article > Web Front-end > How to Create a Responsive Square Div with Aspect Ratio and Centering?
Maintaining Aspect Ratio according to Viewport Dimensions
To achieve a responsive square div that maintains its aspect ratio based on viewport width and height, leverage CSS's aspect-ratio property.
Requirements:
The aspect-ratio Solution
The aspect-ratio property allows you to specify the desired aspect ratio. By default, the property sets the height relative to the width. Therefore, a 1 / 1 aspect ratio creates a square.
<code class="css">.square { aspect-ratio: 1 / 1; background: orange; }</code>
Adapting to Viewport Dimensions
To ensure your square div adapts to the viewport's minimum dimension:
<code class="css">div { max-width: 100vw; max-height: 100vh; margin: 0 auto; /* For centering */ }</code>
Vertical and Horizontal Centering
Centering the square requires setting margin to auto both vertically and horizontally:
<code class="css">div { ... margin: 0 auto; }</code>
Example
<code class="html"><div class="square">Aspect ratio 1:1</div></code>
Conclusion
Using aspect-ratio, you can create responsive square divs that maintain their aspect ratio and are centered within the viewport, ensuring a consistent visual experience regardless of viewport dimensions or orientation.
The above is the detailed content of How to Create a Responsive Square Div with Aspect Ratio and Centering?. For more information, please follow other related articles on the PHP Chinese website!