Home > Web Front-end > CSS Tutorial > How to Create a Responsive Square Div with Equal Height and Width?

How to Create a Responsive Square Div with Equal Height and Width?

Susan Sarandon
Release: 2024-11-11 14:42:03
Original
915 people have browsed it

How to Create a Responsive Square Div with Equal Height and Width?

Responsive Square Div with Equal Height and Width

Your goal is to create a div element that automatically adjusts its height to match its width, regardless of the parent element's size. To achieve this, CSS has a simple and effective solution:

Using Percentage Padding-Bottom:

Add the following CSS to your div:

height: 0;
width: 20%;
padding-bottom: 20%;
background-color: red;
Copy after login

Here's how it works:

  • Set height to 0, making the div initially collapsed.
  • Specify a percentage width (e.g., 20%).
  • Set padding-bottom to the same percentage as the width. This determines the height of the div.
  • The background color is added to make the square visible.

Optional Nested Div:

For more flexibility in content placement, consider creating a nested div within the square div. This allows you to center or align content as needed.

<div>
Copy after login

The above is the detailed content of How to Create a Responsive Square Div with Equal Height and Width?. 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