danijar danijar - 1 month ago 12
CSS Question

How to style a div to be a responsive square?

I want my div to adapt its height to always equal its width. The width is percental. When the parent's width decreases, the box should decrease by keeping its aspect ratio.

How to do this is CSS?

Answer

To achieve what you are looking for you can use the viewport-percentage length vw.

Here is a quick example I made on jsfiddle.

HTML:

<div class="square">
    <h1>This is a Square</h1>
</div>

CSS:

.square {
    background: #000;
    width: 50vw;
    height: 50vw;
}
.square h1 {
    color: #fff;
}

I am sure there are many other ways to do this but this way seemed the best to me.