Tips for implementing a responsive Object fit cover on an image card in Boostrap 4

Is there a way to maintain the responsive layout of Bootstrap 4 while applying object-fit: cover; to an image in a card element? This would help ensure that the image fits properly without sacrificing responsiveness.

#imgUNcover {
  width: 285px;
  height: 145px;
  -o-object-fit: cover;
  object-fit: cover;
  -o-object-position: center;
  object-position: center;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<div class="col-12 col-md-6 col-lg-3 mb-3 mb-md-3">

  <div class="card">

    <div class="img-container">

      <a href="index.php?post=<?php echo $UN['title']?>"><img src="<?php echo $UN['capa']?>" alt="<?php echo $UN['alt']?>" class="card-img-top" id="imgUNcover"></a>

    </div>

    <div class="card-body">

      <a href="index.php?post=<?php echo $UN['title']?>" class="card-title cardTitleLink">
        <h1 class="cardTitleUN">
          <?php echo $UN['title']?>
        </h1>
      </a>

      <p class="card-text text-muted">
        <?php echo $UN['text']?>
      </p>

      <a href="index.php?post=<?php echo $UN['title']?>" class="btn btn-outline-danger btn-sm">Continue Lendo</a>

    </div>

  </div>

</div>

If we don't apply object-fit: cover;:

https://i.sstatic.net/HTIbp.png

But with object-fit: cover;:

https://i.sstatic.net/ZtanO.png

Although changing the width of the image using the id #imgUNcover may not fully address the issue on different screen resolutions.

Edit:

https://i.sstatic.net/CurrT.png

Answer №1

Susi, I'll take a bit of a risk here and try to guess what you're looking for. Let me know if you need something different, and I'll adjust the answer accordingly.


If you want an image to resize based on its containing block size, you can use a percentage value for the height or width. See the code example below:

Additional Insights (for those interested in more details):

  • You don't have to set both height and width on the image element
  • It's recommended but not mandatory
  • The unused dimension defaults to auto, resulting in a calculated value equal to:
    used value of other dimension / intrinsic image ratio
  • This ensures the aspect ratio remains consistent with the image's intrinsic aspect ratio
  • When using a % value, ensure the container block has that particular dimension set
  • Setting no height/width results in the content box adjusting to the intrinsic dimensions of the image
  • Object-fit property only affects images with different aspect ratios than the set dimensions

Closing Words:

  • A lot of notes, but hopefully helpful in understanding how inline replaced elements' height / width function
  • Check out CSS2.1 spec for info on height / width of various elements here
  • For more on object-fit, visit MDN article here

Code Sample:

#imgUNcover {
  width: 100%;
  object-fit: contain;
}
Add your HTML code here...

Try resizing the browser using this pen: Resize Browser Pen


UPDATE (added functionality as requested in comment):

To ensure all images are the same height, set a specific height on the cards and distribute it using flexbox's flex-basis property for the image and body sections of the card. Use overflow: auto to prevent items from extending the container.

Modifying Bootstrap requires attention to detail due to conflicting properties. Often "!important" is needed to override these.

New Styling:

.card {
  height: 400px;
}

.img-container {
  flex: 1 0 30% !important;
  overflow: hidden;
}

.card-body {
  flex: 1 0 60% !important;
  overflow: auto;
}

#imgUNcover {
  width: 100%;
  height: 100%;
  object-position: 50% top;
  object-fit: cover;
}
Add your modified HTML code here...

Explore the updated pen here: Updated Pen Link

Adjust object-position and object-fit properties to customize image placement.


Final Edit:

Checkout the improved pen with scrollbar enhancements: Improved Pen

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

What steps do I need to take in order to load the static folder from a CSS file?

Is there a way to load the static folder from a CSS file? I attempted to import using URL(), however, it was unsuccessful. I am looking to utilize the static path in order to apply a background to an element. .input_card:checked+.check-box { backgroun ...

Activate the scrollbar solely in case of content overflow

I have a situation in my code where I am using overflow-y: scroll to create a scroll bar with a maximum height of 40px. This setup works perfectly fine in the Chrome browser, as the scroll bar is only visible when there is overflow content (i.e. text exten ...

What is the correct way to create a card outline in Bootstrap?

I am currently developing a Django website to enhance my skills in coding, CSS, Html, and Bootstrap. However, I am encountering an issue with the main page of my site. The visuals on my cards do not align properly with the colored boxes at the top of the p ...

CSS form not aligning properly within wrapper div and appears to be floating outside of it

I am in the process of creating a website that includes a wrapper div containing a: -Header -Content -Footer The issue I am encountering is when I insert regular text into the content section, everything displays properly and the background stretches s ...

Guide to creating a modal that redirects to a URL using react and bootstrap

I created a button that triggers a Modal on a React Component. //REACT COMPONENT import React from 'react'; import { Link, withRouter } from 'react-router-dom'; const BottomNavBar = ()=>{ return ( ...

Issue with Dynamic Theming in Ionic Framework

Currently, I am using Ionic in combination with Angular to create an App. I have introduced dynamic theming by adding two .scss files into my theme folder. In my app.scss file, I define the layout of components without colors, while all color styles are st ...

Tips for utilizing JavaScript getElementByClassName to retrieve all the elements within a ul without having to specify the class name in each li

Looking to tidy up my HTML/CSS. Is there a way to keep this JavaScript functioning without needing to add the class name to every li element within the ul? Any suggestions on how to improve the visual appeal and readability of the HTML code? const Profi ...

Is it possible to enable a dropdown menu to appear when clicking on a text input field using HTML?

I'm on a quest to discover how to craft a text input field that becomes clickable, revealing an HTML dropdown rather than a typical select box (similar to the concept of a bootstrap mega menu ) I haven't quite cracked the code on what the HTML s ...

What is the best way to place text alongside a shape?

I'm attempting to place text beside the circular shape. HTML <div class="row"> <div class="col-sm-2"> <span><div class="circle"></div></span><p>available</p> </div> </div> C ...

Tips on delaying Bootstrap 3 carousel with setTimeout

I have a unique situation with my page where I have nine different carousels, each needing to start at different times. How can I achieve this? Would using the setTimeout function be the solution? Can someone provide guidance on how to make this work? Belo ...

What is the best way to present both paragraphs and images from a div in a sequential order

Currently, I am developing a compact web tool to assist editors in creating content by utilizing buttons to insert paragraphs and images. The elements are saved with an ID (beginning at 0 and increasing for each new element) and can be previewed in a div n ...

Checking boxes on Android for compatibility with Firefox, Chrome, and Internet Explorer 8

Could anyone assist me with finding Android checkboxes styled with CSS and/or jQuery for my project? I haven't been able to find any resources or plugins that could help. Any links you can provide would be greatly appreciated as I've come up empt ...

What is the best way to conceal a specific class of DIV within a container, and how can I also hide another DIV within the same container by

I have a DIV class containing around 10 elements within a container. I am looking to implement a feature where these elements are hidden and shown one by one every 15 seconds using jQuery with a smooth fadeOut() effect. Your assistance in achieving this wo ...

Adding space between the cells on the far left and far right of the table and the border

I need some advice on creating a table in HTML where the borders of the leftmost and right most cells do not extend all the way to the edges of the table. Here's an example: | ____ | In this example, the top border of the cells is continuous within ...

Adding design to distinct element after clicking a button

Struggling with a JS/Jquery issue on my portfolio website, I admit that I am still just an average programmer. My portfolio website has five buttons, each representing a different project. For each project, there is a corresponding text description and an ...

Remove the styling from child elements in Google Maps InfoWindow by utilizing jQuery

Greetings to all the brilliant minds on Stackoverflow! Just like many others seeking customization for InfoWindow, I am also on a quest to make it happen. Please note: Due to technical constraints, using infobubble and infobox is not an option for m ...

"Scrolling with Bootstrap Scroll Spy is causing incorrect sections to be

Can anyone help me with my issue regarding Bootstrap scrollspy settings? It seems to be highlighting the wrong div id, always the last one. Here is the code snippet: Content: <body style="heigt: 100%" data-spy="scroll" data-target="#side-menu"> ...

How can I retrieve the offset top of a td element in relation to its parent tr element?

Here is some sample dummy HTML code: <table> <body> <tr> <td id="cell" style="height: 1000px; width: 200px;"></td> </tr> </body> </table> I am looking to attach a click event ...

Tips for centering a list using flexbox technique

I have 3 boxes stacked vertically using flexbox, currently positioned to the left. I am looking for a more elegant solution to center them horizontally without compromising the layout. I attempted using margin: 10px auto on a div which seemed awkward in th ...

What's the best way to apply a margin top to an image using Tailwind CSS?

Is there a way to adjust the top margin of an image in Tailwind CSS? I'm having trouble making my logo clearly visible and think giving it some space at the top might help. How can I do this within the Tailwind CSS framework? https://i.sstatic.net/Ae ...