Setting a specific height for images in Bootstrap 4 and keeping it

I'm currently utilizing Bootstrap's 4 grid system to showcase images of varying sizes from unsplash.com on a webpage.

However, I'm facing an issue in figuring out how to create a fixed-sized thumbnail for all images that can fit into their respective containers regardless of their height.

Below is a sample code snippet:

<!DOCTYPE html>
            <html lang = "en">

            <head>
                <meta charset = "UTF-8" />
                <meta name = "viewport" content = "width=device-width, initial-scale=1.0" />
                <title> Document </title>
                <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
                    integrity = "sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
                    crossorigin = "anonymous" />
            </head>

            <body>
                <div class = "container-fluid mt-5 py-3 py-md-5">
                    <div class = "row text-center text-lg-left">
                        <div class = "col-lg-3 col-md-4 col-6">
                            <a asp-area = "" asp-controller = "Gallery" asp-action = "WeddingPhoto">
                                <img class = "image-card img-fluid img-thumbnail" src = "" alt = "" />
                            </a>
                        </div>
                        <div class = "col-lg-3 col-md-4 col-6">
                            <a asp-area = "" asp-controller = "Gallery" asp-action = "WeddingPhoto">
                                <img class = "image-card img-fluid img-thumbnail" src = "" alt = "" />
                            </a>
                        </div>
                        <div class = "col-lg-3 col-md-4 col-6">
                            <a asp-area = "" asp-controller = "Gallery" asp-action = "WeddingPhoto">
                                <img class = "image-card img-fluid img-thumbnail" src = "" alt = "" />
                            </a>
                        </div>
                        <div class = "col-lg-3 col-md-4 col-6">
                            <a asp-area = "" asp-controller = "Gallery"
                                asp-action = "WeddingPhoto">
                                <img class = "image-card img-fluid img-thumbnail" src = "" alt = "" />
                            </a>
                        </div>
                    </div>
                </div>
                <!-- jQuery first, then Popper.js, then Bootstrap JS -->
                <script src = "https://code.jquery.com/jquery-3.4.1.slim.min.js"
                    integrity = "sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin = "anonymous"></script>
                <script src = "https://cdn.jsdelivr.net/npm/cfprotect/__cf_email__" data-cfemail = "dbabb4ababbea9f5b1a89beaf5eaedf5eb">@</a>/dist/umd/popper.min.js"
                    integrity = "sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin = "anonymous"></script>
                <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
                    integrity = "sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
                    crossorigin = "anonymous"></script>
                <script>
                    const imageCards = document.querySelectorAll(".image-card");
                    const url = "https://source.unsplash.com/collection/308700/300/?sig=";

                    const randomNum = () => {
                        return Math.floor(Math.random() * 100000);
                    };

                    for (let image of imageCards) {
                        let src = `${url}${randomNum()}`;
                        image.setAttribute("src", src);
                    }
                </script>
            </body>

            </html>

https://i.sstatic.net/bdOPG.jpg

Is there a specific Bootstrap class that I can use to maintain consistent image height and ensure fitting within the parent div?

Answer №1

I utilize the padding top technique to achieve the desired aspect ratio for the image, allowing me to position it absolutely within the anchor tag and apply object fit (potentially requiring a polyfill for Internet Explorer):

@import url('https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css');

/* prefer classes over element selectors */

a {
  display: block;
  padding-top: 56.25%;
  position: relative;
}

a>img {
  display: block;
  width: 100%;
  height: 100%;
  max-height: 100%;
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
}
<div class="container-fluid mt-5 py-3 py-md-5">
  <div class="row text-center text-lg-left">
    <div class="col-lg-3 col-md-4 col-6">
      <a asp-area="" asp-controller="Gallery" asp-action="WeddingPhotos">
        <img class="image-card img-fluid img-thumbnail" src="https://www.fillmurray.com/200/300" alt="" />
      </a>
    </div>
    <div class="col-lg-3 col-md-4 col-6">
      <a asp-area="" asp-controller="Gallery" asp-action="WeddingPhotos">
        <img class="image-card img-fluid img-thumbnail" src="https://www.fillmurray.com/300/300" alt="" />
      </a>
    </div>
    <div class="col-lg-3 col-md-4 col-6">
      <a asp-area="" asp-controller="Gallery" asp-action="WeddingPhotos">
        <img class="image-card img-fluid img-thumbnail" src="https://www.fillmurray.com/300/200" alt="" />
      </a>
    </div>
    <div class="col-lg-3 col-md-4 col-6">
      <a asp-area="" asp-controller="Gallery" asp-action="WeddingPhotos">
        <img class="image-card img-fluid img-thumbnail" src="https://www.fillmurray.com/200/400" alt="" />
      </a>
    </div>
  </div>
</div>

Answer №2

To tackle this issue, you could try defining a specific height for the img-thumbnail and applying object-fit property to it:

<style>
.img-thumbnail {
  height: 300px;
  object-fit: contain;
}

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

Steps to click on a link within a span element contained within an anchor element with a specific class using XPath

When using xpath, sélénium is not recognizing the element. What would be the correct xpath to use? HTML: <a class="xmi" onclick="this.focus();return false; "href="#"> <span title="">SITE A</span> </a> XML locator file: <do ...

Adapt to screen size changes by transforming a single row into two separate rows

I am trying to create a two-column row with inputs: <div class="row first-row"> <div class="column col-6"> <div class="form-group"> <label for="usr" >Se ...

CanvasJS with a see-through background

I am looking to make my CanvasJS background transparent, but I'm having some issues. The backgroundColor property is used in CanvasJS to set the color of the canvas background. When I tried entering "None" instead of a color code, it ended up giving ...

Having trouble with changing the class using Jquery click function

Originally, I had the code in an ASP.Net project, but to troubleshoot, I moved it to a separate web server. However, I am still unable to switch between the tab panes with the buttons. Any assistance in debugging this issue would be greatly appreciated. S ...

Javascript variable unable to retrieve value from textbox

Hey there! I am having some trouble reading a textbox that is populated from the server into a JavaScript variable. When I try to access it, I get a console error saying "can't read from NULL". However, the text box is definitely populated with the st ...

Troubleshooting sound problems in Angular JS

Can anyone help with pausing an AngularJS audio when the browser window is closed and resuming it when the window is maximized? I'm new to AngularJS and have no idea how to achieve this. var app=angular.module("myApp",['ngAudio']); ...

Issues with Functioning of Control Buttons in Bootstrap 4 Carousel

Can someone please help me troubleshoot an issue with Bootstrap 4 carousel controls? I've been trying to figure it out on my own for about an hour, but I'm stumped. Any assistance would be greatly appreciated! I've followed the Bootstrap do ...

checkbox causing the button to appear empty

Due to the inability of a ngIf and ngFor to coexist, I added an ng-container to facilitate the loop. However, after making this change, nothing seems to be working as expected without any clear reason. Below is the code snippet that is causing trouble: Vi ...

Ways to substitute numerous instances of a string in javascript

I have experience in developing websites using reactjs. I usually implement restAPI's with java and work with liferay CMS. In one of my projects, I created a shortcode for accordion functionality like this: ('[accordion][acc-header]Heading 1[/ac ...

Tips for positioning social media icons on the right side of the navigation bar

I need assistance aligning my social media icons with the navbar on the right side of the display. Can someone provide guidance? The first image shows the current layout, while the second image illustrates how I would like it to appear: http://imgur.com/a ...

Adjust tool tip text on the fly

As a beginner, I created a test table and now I want to make the tool tip text change dynamically when I hover over the table with my mouse. Ideally, I would like the tool tip text to correspond to the content of the table cell. Currently, I only have stat ...

Using a link in React to open a subroute instead of navigating to a new page

item.link = "www.google.com" <a href={item.link} target="_blank" rel="noopener noreferrer">{item.about}</a> The code snippet above creates a link to an external website using the provided URL. ...

Enclose an image with a <div> element while maintaining the <div> height at

Encountering a challenge where positioning an element on top of an image at specific coordinates (20% from the top and 30% from the left) is required. Initially, the solution involved wrapping the image in a div with a relative position and using absolute ...

The Bootstrap 4.6.1 Carousel is designed to display all carousel items simultaneously, even when only one item is currently active

I've been struggling to create a MySQLi recordset-driven Bootstrap carousel. Despite my efforts, all the slides are displaying at once instead of one item being active on load. <div id="myCarousel" class="carousel slide" data-ri ...

The art of expertly placing the arrow in <details> with CSS

I'm looking to adjust the placement of the arrow within details. I've experimented with using float:left, but when the line is too long, like in the example provided, the arrow shifts to the beginning of the line below when I resize the window. I ...

"Troubleshooting: Why isn't my jQuery AJAX POST request successfully sending data to

Here is the jQuery code snippet that I am currently working with: $("#dropbin").droppable( { accept: '#dragme', hoverClass: "drag-enter", drop: function(event) { var noteid = "<?=isset($_POST['noteid']) ? ...

How can you deselect nested checkboxes while maintaining the currently selected checkbox using jQuery?

In my WordPress site, I have a structure of nested checkboxes within ul and li elements. Here is the HTML code: <ul class="woof_list woof_list_checkbox"> <li> <label class="woof_checkbox_label" for="woof_uncheck">Parent Categor ...

The link button appears unselected without a border displayed

I am facing an issue with a link button in my code. Here is the snippet: <div class="col-2"> <a type="button" routerLink="auto-generate-schedules/generate" class="btn btn-primary mb-2">Generate Sche ...

What is the best way to generate unique mousedown callbacks on the fly?

My goal is to create multiple divs, each with a unique mousedown callback function. However, I want each callback function to behave differently based on the specific div that is clicked. Below is the code I have been using to create the divs and set the ...

What is the best way to create text boxes that can expand and collapse within a UIWebView?

I am looking to present text in a UIWebView with expandable or collapsible boxes that contain titles. The user should be able to tap the bar of a collapsed box to expand it. Is there a simple solution available that can be easily integrated into a local ...