Preserve the aspect ratio when using horizontal flex cards

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>

Answer №1

Check out this demo showcasing the aspect-ratio property with backwards compatibility for older browsers. The card layout used here is inspired by Bootstrap.

For best viewing experience, please click on "Full Page"

.mycard .card-img {
  aspect-ratio: 16 / 9;
  object-fit: cover;
}


/*Old Browser Support*/

@supports not (aspect-ratio: 16 / 9) {
  .mycard {
    position: relative;
    height: 0;
    padding-bottom: 56.25%;
  }
  .mycard .card-img {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    bottom: 0;
    background: red;
    /* just for illustration */
  }
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<div class="card mb-3" style="max-width: 540px;">
  <div class="row no-gutters">
    <div class="col-md-4">
      <div class="mycard">
        <img src="https://via.placeholder.com/150" class="card-img" alt="">
      </div>
    </div>
    <div class="col-md-8">
      <div class="card-body">
        <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
        <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
      </div>
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The conversion of string to number is not getting displayed correctly when using console.log or document.write. Additionally, the concatenated display is also not functioning as intended

Being new to JS and HTML, this program was created to enhance my understanding of the concepts. I attempted a basic program to convert a string to a number in three different ways, but I am having trouble determining if the conversion actually took place. ...

What is the best way to duplicate a complete row?

I am looking to create a form that includes an "Add Row" button. When this button is clicked, a new row should be generated, identical to the last row. The rows contain dropdown values, and I want the new row to display the same dropdown options as the p ...

The $(Document).ready function does not trigger in the code but functions properly when executed in the console

I'm having an issue with a script that works in the console but not on the actual code. I tried using $(windows).ready, but it still doesn't work. Here is the script: <script> console.log('1') $(document).ready(function( ...

Functionality not working when clicked on iPhones

I'm facing an issue with my dropdown menu that appears when an image is clicked. Below is the relevant HTML code snippet: <div class="menu"> <img id="menu_img" src="https://res.cloudinary.com/dqn5eqmwt/image/upload/v1493014197/Menu ...

execute a jQuery number counter when scrolling is detected

My jQuery number counter is working perfectly, but it starts running as soon as the page loads. I'm trying to figure out how to make it run only when the element comes into view. Here is my current code: EDIT After some tinkering, I achieved the des ...

Show a compact graphic in the upper-right-hand corner

Hey, I have this interesting idea but CSS isn't my strong suit. Any thoughts on how to achieve it? I'm looking to create a new class that, when applied to an item (like a div), displays a small clickable pre-defined image in the Top-Right corne ...

issues with the visual studio website code (Struggling to establish a connection between the site and a database)

Currently, I am in the process of developing a website using Visual Studio and attempting to connect it to a Microsoft SQL Server 2014 database. My learning journey has led me to a tutorial video on YouTube focusing on creating a coffee-themed website alon ...

User information in the realm of website creation

Can someone provide insight on where user data such as photos, videos, and posts is stored? I doubt it is saved in an SQL database or any similar system. ...

Changing the line spacing of label elements in HTML forms

I am encountering an issue with my form where the spacing between the two lines of the <label> element is too large and I am unable to adjust the line-height. For reference, I have applied the same CSS styles to a <label> and a <p>. Surp ...

sophisticated adhesive manipulation

I am in the process of making certain elements sticky or fixed within an Angular project. Thus far, I have successfully managed both static and dynamic elements. The left menu remains static while the main content will be dynamic. The main content include ...

Stop the window from scrolling downwards

My website has a full-width slider as the main background and I am using jQuery to show or hide divs depending on the clicked link. However, when some sections are longer than the initial view, my page automatically scrolls to the bottom after a click. How ...

Interactive horizontal slideshow for hyperlinks - bootstrap framework and model-view-controller architecture

I am currently working on an MVC project that utilizes Bootstrap. My requirement is to have a horizontal menu of links that can slide left and right using arrows (similar to a carousel, but for links instead of images). To be more specific, the menu need ...

Arrange the inline-block elements at the bottom of a div

Hey there! I'm currently working on designing a website header using bootstrap 3, which consists of four main divs. Within each of these divs, there are two nested divs. Imagine one of the initial divs as shown below: _______________________________ ...

The swiper slider loop malfunctions when the number of slides is less than the double-value

When using **6 slides** with slidesPerView: 3, everything works fine. However, if I use 5 slides and set slidesPerView: 3, the loop stops after the last slide. var swiper = new Swiper('.swiper-container', { direction: 'ver ...

Tips for centering text in a react flexbox layout

Utilizing react-flexbox-grid in my project has led to the following layout: const SpicyMenu = (props) => ( <List> {props.foodItems.map(foodItem => <SpicyMenuItem key={foodItem.name} {...foodItem}/>)} </List> ); co ...

Displaying JQuery dialogs briefly show their contents before the page finishes loading

Utilizing jquery 1.10.3, I am creating a dialog that is quite intricate. When I say 'intricate', I mean that the dialog's content includes data from a database, such as dropdown lists populated by the results of database queries, alongside s ...

What is preventing me from accessing a dialog form modal through a button using JavaScript with jQuery?

There is jQuery and Bootstrap code on the same page, let's call it index.html This is my unique content <button id="btncreate" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Create</button> I am having trouble acces ...

Tips for placing the footer at the very bottom of your webpage

After attempting to place the footer at the bottom, I encountered some strange behavior. I am using mui framework. I decided to create a simple example page to illustrate how the footer should be positioned. The code in app.js is as follows: <> < ...

When I try running my JavaScript code in the console, it works perfectly fine. However, I encounter an error when I attempt

Recently, I added a cool JavaScript code to my website that changes the background of the landing page randomly. Here is the snippet: var bgImages = [ "url('assets/bg/front1.jpg')", "url('assets/bg/fro ...

The CSS will dynamically adjust the width of the DIVs based on the browser size, allowing for more DIVs per

I am currently designing a layout to showcase content blocks side by side in a manner that fills the browser window with DIV blocks. I recall stumbling upon a CSS-only technique that automatically adjusts the width of each DIV based on the size of the bro ...