Fixing Aspect Ratio with CSS (LESS)

css
2017-06-18 23:07 (7 years ago) ytyng

It's a common one, but I always forget it.

.aspect-ratio(@ratio) {
position: relative;
&:before {
content: "";
display: block;
padding-top: @ratio;
}
> .content {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
}
}

.aspect-ratio(@width, @height) {
.aspect-ratio(@height / @width * 100%);
}

.pickup-article-image-box {
.aspect-ratio(16, 9);

img {
// object-fit: contain; // Aspect Fit
object-fit: cover; // Aspect Fill
}
}

 <div class="pickup-article-image-box">
<img class="unveil content" data-src="{{ post.image_url }}" />
</div>

Currently unrated
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.

Archive

2025
2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011