Home  >  Article  >  Web Front-end  >  How to Create a Responsive Square Div with Aspect Ratio and Centering?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 03:46:03775browse

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>

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!

Statement:
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