Make a square when there is a dynamically changing width based on percentage [duplicate]

There are 3 main techniques to keep the aspect ratio of a responsive element.
The first one is by far the best and will work for a variety of use cases : the aspect-ratio CSS property. The 2 others may suit other use cases : using padding or vw units :
(for a complete solution for a responsive grid of squares, you can see this answer)

The aspect-ratio property

This specifies directly the aspect ratio of and element. It can be based on the width or height of the element. (see MDN)
Here is an example :

body {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}

div {
  width: 23%;
  margin-bottom: 2%;
  background: gold;
  aspect-ratio: 1/1;
}
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

Using vw units

You can use vw units to make your elements square and responsive (viewport units on MDN).
1vw = 1% of viewport width so you can set the height of the elements according to the width of the viewport (or height with vh units).
Example with a 4×4 grid :

body{
  margin:0;
  display:flex;
  flex-wrap:wrap;
  justify-content:space-around;
}

div{
    width:23vw; height:23vw;
    margin:1vw 0;
    background:gold;  
}
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>

The same behaviour can be achieved sizing the element according to the viewport height using vh units.


Using padding

Padding is calculated according to the container’s width so you can use it to set the height of block according to its width.
Example with a 4×4 grid :

.wrap {
    width:80%;
    margin:0 auto;
}
.wrap div {
    width:23%;
    padding-bottom:23%;
    margin:1%;
    float:left;
    background:gold;
}
<div class="wrap">
    <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)