A Perfect Square with CSS
Make a perfect square with CSS that fluidly adjusts to the width of its container. Thanks Dave Rupert for this trick.
Step 1: Add an empty DIV tag
There’s only one line of HTML for this project. It’s an empty DIV tag.
<div></div>
Now, let’s add a class that we can target. The class you use is only limited by your imagination! However, I recommend using something simple and descriptive like class=”square”
.
<div class="square"></div>
Step 2: Style the DIV so its height is equal to its width
Style the .square
to have a width
of 100%
, a height of 0
and set the top
padding to 100%
.
.square {
width: 100%;
height: 0;
padding-top: 100%;
}
If you want to see your square you can add a background color or border.
Edit from @jameel_51660 via the comments: If you want to add a border you can use box-sizing: border-box
so that the border you add doesn’t add to the overall height and width of the square.
.square {
width: 100%;
height: 0;
padding-top: 100%;
background-color: #ccc;
}
That’s it! You have a perfect square that will fit inside of any container you place…