How to Create a Responsive Square Div with Aspect Ratio and Centering?

Mary-Kate Olsen
Release: 2024-11-02 03:46:03
Original
783 people have browsed it

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:

  • Pure CSS
  • Square adapts to the viewport's minimum dimension regardless of orientation
  • Horizontal and vertical centering within the viewport

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>
Copy after login

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>
Copy after login

Vertical and Horizontal Centering

Centering the square requires setting margin to auto both vertically and horizontally:

<code class="css">div {
  ...
  margin: 0 auto;
}</code>
Copy after login

Example

<code class="html"><div class="square">Aspect ratio 1:1</div></code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!