I have successfully created a vertical flex card with an image on top that maintains a 16:9 aspect ratio at all times. Here is the code for my vertical flex card:
.card {
display: flex;
flex-direction: column;
margin: 0.75rem;
}
.card .card-img {
position: relative;
padding-bottom: 56.25%;
}
.card .card-img img {
position: absolute;
object-fit: cover;
width: 100%;
height: 100%;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.card .card-body {
margin-bottom: 0.75rem;
display: flex;
flex-direction: column;
}
.card .card-body a {
text-decoration: none;
font-size: clamp(1rem, 0.6505rem + 0.9709vw, 1.5rem);
color: #3e3700;
font-weight: 500;
}
.card .card-body .card-title {
font-size: clamp(1.125rem, 0.5133rem + 1.699vw, 2rem);
font-weight: 500;
line-height: 1;
}
.card .card-body .card-description {
font-size: clamp(1rem, 0.6505rem + 0.9709vw, 1.5rem);
font-weight: 300;
margin-bottom: 0.75rem;
}
<div class="card">
<div class="card-img">
<img
src="https://via.placeholder.com/150"
alt="img"
/>
</div>
<div class="card-body">
<h2 class="card-title">
Lorem ipsum dolor sit, amet consectetur
adipisicing elit. Ratione, cumque?
</h2>
</div>
</div>
Now I am facing a challenge in making it horizontal. When I try to change the flex-direction to row using flex-direction: row;
, it doesn't work as expected. I want the image to maintain a 16:9 aspect ratio even in horizontal mode. Here is my progress so far:
.card {
display: flex;
flex-direction: row;
margin: 0.75rem;
}
.card.card-h .card-img {
width: 40%;
}
.card.card-h .card-body {
width: 60%;
}
.card .card-img {
position: relative;
padding-bottom: 56.25%;
}
.card .card-img img {
position: absolute;
object-fit: cover;
width: 100%;
height: 100%;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.card .card-body {
margin-bottom: 0.75rem;
display: flex;
flex-direction: column;
}
.card .card-body a {
text-decoration: none;
font-size: clamp(1rem, 0.6505rem + 0.9709vw, 1.5rem);
color: #3e3700;
font-weight: 500;
}
.card .card-body .card-title {
font-size: clamp(1.125rem, 0.5133rem + 1.699vw, 2rem);
font-weight: 500;
line-height: 1;
}
.card .card-body .card-description {
font-size: clamp(1rem, 0.6505rem + 0.9709vw, 1.5rem);
font-weight: 300;
margin-bottom: 0.75rem;
}
<div class="card card-h">
<div class="card-img">
<img
src="https://via.placeholder.com/150"
alt="img"
/>
</div>
<div class="card-body">
<h2 class="card-title">
Lorem ipsum dolor sit, amet consectetur
adipisicing elit. Ratione, cumque?
</h2>
</div>
</div>