JSFiddle - React, Tailwind, and code Playground
by mrnobody
HTML
<div class="container-img ratio-16-9">
<img src="http://img1.goodfon.ru/original/640x480/6/a2/ptica-sova-progulka-shagaet.jpg" alt="">
</div>
<div class="container-img ratio-4-3">
<img src="http://img1.goodfon.ru/original/640x480/6/a2/ptica-sova-progulka-shagaet.jpg" alt="">
</div>
<div class="container-img ratio-w300-h200">
<img src="http://img1.goodfon.ru/original/640x480/6/a2/ptica-sova-progulka-shagaet.jpg" alt="">
</div>
CSS
body {
font-family: sans-serif;
}
.container-img {
position: relative;
height: 0;
overflow: hidden;
background-color: #8A8A8A;
margin-bottom: 2em;
}
.container-img > img {
position: absolute;
left: 0;
top: 50%;
width: 100%;
height: auto;
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
}
.ratio-16-9 {
padding-top: 56.25%;
}
.ratio-4-3 {
padding-top: 75%;
}
/*
Ширина картинки 300px, а высота должна быть 200px,
мы высоту делим на ширину и умножаем нв 100%
(200 / 300) * 100% = 66.66666666666667%
*/
.ratio-w300-h200 {
padding-top: 66.66666666666667%;
}
.ratio-16-9:after, .ratio-4-3:after, .ratio-w300-h200:after {
font-size: 0.75em;
position: absolute;
top: 10px;
right: 10px;
padding: 5px;
background-color: rgba(255, 255, 255, 0.78);
}
.ratio-16-9:after {
content:"Соотношение сторон 16:9";
}
.ratio-4-3:after {
content:"Соотношение сторон 4:3";
}
.ratio-w300-h200:after {
content:"Соотношение сторон 300:200 (3:2)";
/* либо 3:2*/
}