Home  >  Article  >  Web Front-end  >  How to Create a Responsive, Square-Shaped Div in CSS?

How to Create a Responsive, Square-Shaped Div in CSS?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 18:44:03814browse

How to Create a Responsive, Square-Shaped Div in CSS?

Creating a Responsive, Square-Shaped Div

Question:

How can you design a div element in CSS to maintain a square aspect ratio, adjusting its height proportionally to its width, as the parent element resizes?

Answer:

There's a simple technique to achieve this using padding:

  1. Set the height of the div to 0. This "tricks" the browser into making the height flexible.
  2. Define the div's width as a percentage.
  3. Set the padding-bottom to the same percentage as the width. This forces the browser to adjust the height to maintain a square aspect ratio.

Here's a code sample:

<div>

The outermost div establishes the square shape, while the inner div contains the actual content. This approach effectively maintains a square aspect ratio as the parent element's width changes. It's compatible with most browsers.

A live example can be found on jsfiddle: [insert jsfiddle link here]

The above is the detailed content of How to Create a Responsive, Square-Shaped Div in CSS?. 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