To achieve the desired result, consider using the top/bottom padding
property in percentage.
Check out this example.
.box {
width: 25%;
padding-bottom: 25%;
}
The use of a percentage value on top/bottom padding
or margins
is relative to the width of the container block of the box.
8.4 Padding properties: 'padding-top', 'padding-right', 'padding-bottom', 'padding-left', and 'padding'
<percentage>
The percentage is calculated with respect to the width of
the generated box's containing block, even for 'padding-top' and
'padding-bottom'.
Adding Content
If you want the height of the box to adjust dynamically with added content, one approach is to wrap the content within an element called .wrapper
and position it absolutely relative to the box. Then, utilize the top
, right
, left
, and bottom
properties to fill the entire space of the box.
View this example
<div class="box">
<div class="wrapper">
<!-- Your content here... -->
</div>
</div>
.box {
width: 25%;
position: relative;
}
.box:after {
content: "";
display: block;
padding-top: 100%; /* 1:1 square */
}
.box > .wrapper {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
}
For more information, you can refer to this answer (Responsive Container section).