Menu

Surprisingly useful CSS glitch

1 min read October 24, 2018 at 12:49pm on css

Today a colleague wanted to make some divs square.

My first reaction was: 'I doubt this can be done with only CSS', but he proved me wrong.

There is an example at http://www.mademyday.de/css-height-equals-width-with-pure-css.html that uses two divs with specific positioning to accomplish this task.

But the most interesting part was the padding-top value used in the example. It's 100%, but there is no height set, so it falls back to use the width for it's calculation.

Anybody else has a hard time wrapping his/her head around padding-top being calculated from the width? I mean, it's Y-axis and X-axis all mixed up...

But it works well in all browsers tested, so it's definitely not some implementation error.

Here is the way we adopted it into our CSS file:

<style>
.ratioBox {
position: relative;
width: 100%;
}
.ratioBox:before {
content: "";
display: block;
padding-top: 100%;
}
.ratioBox>.ratioContent {
position: absolute;
top:0;
right:0;
bottom:0;
left:0;
background-size: cover;
}
</style>
<div class="ratioBox">
<div class="ratioContent"
style="background-image:url(https://loremflickr.com/400/400/cat)">
so squared
</div>
</div>