Creating a responsive bootstrap card-tall for mobile devices

I'm currently using Bootstrap cards to create a gallery-like display of images. To style the images, I'm also utilizing the card-tall class. Since these images are posters, they naturally occupy a lot of space.

Here's how it appears on the website:

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

However, on mobile devices, it looks like this:

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

The HTML structure for the posters is enclosed within a div:

 <div id = "all" class="photo-grid">
       <div class="card card-tall" style="background-image:url(./img/portfolio/poster1.jpg)" >
       </div>
       <div class="card card-tall" style="background-image:url(./img/portfolio/poster4.jpg)">
       </div>
</div>

Along with the CSS code:

* {
  box-sizing: border-box;
}
body {
  background: #fff;
  color: #fff;
  font-family: "Noto Sans", sans-serif;

}
.photo-grid {
  height: 100%;
  display: grid;
  gap: 1rem;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  grid-auto-rows: 240px;
  margin-right: 10%;
  margin-left: 10%;
  margin-bottom: 3rem;
}
.card {
  height: 100%;
  width: 100%;
  border-radius: 4px;
  transition: transform 200ms ease-in-out;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

@media screen and (min-width: 600px) {
  .card-tall {
    grid-row: span 2 / auto;
  }
  .card-wide {
    grid-column: span 2 / auto;
  }
}



/* import fonts  */ 
 @import url('https://fonts.googleapis.com/css2?family=Montserrat&display=swap'); 

/* css variables */ 
@import url(./partials/_variables.css); 

/* import global styling */ 
@import url(./partials/_global.css);

I need some assistance with this setup!

Answer №1

There are two primary purposes for incorporating images in HTML:

  • background-image - These images are not considered content and are displayed within the element's boundaries without altering its size.
  • Regular images: <img>s - These images are treated as content and, among other things, determine the size of their parent element (unless positioned outside the flow using position, which seems to be your objective).

The simplest way to ensure that an element's height fits the image without cropping is by using the background image as an actual <img>:

<div class="card card-tall" style="background-image:url(./img/portfolio/poster1.jpg)" >
  <img src="./img/portfolio/poster1.jpg">
</div>

...along with this CSS code:

.card-tall img {
  display: inline-block;
  width: 100%;
  height: auto;
  visibility: hidden;
}

Although the image will define the card's aspect ratio, what you see will still be the background-image due to the <img> element having a hidden visibility - it won't be rendered.

It's worth noting that this method doesn't add any extra weight to the page since the resource is the same for both the background-image and the <img>.

If you only want this behavior on particular screen sizes, encapsulate the CSS within the appropriate @media query.


To avoid custom CSS, apply these classes directly to the <img>:

<img src="./img/portfolio/poster1.jpg"
     class="d-inline-block w-100 h-auto invisible">

The drawback is that each utility class (like most Bootstrap classes) includes !important. For responsive design, if you don't want the images displaying on medium screens (md and up), use the d-md-none class (adjust as needed, e.g., d-sm-none, d-lg-none, etc.).


Note also that images can be added programmatically using the following jQuery script:

$(function() {
  $('.card-tall').each(function() {
    $(this).append($('<img />', {
      class: 'd-inline-block w-100 h-auto invisible',
      src: $(this).css('backgroundImage').replace('url("', '').replace('")', '')
    }))
  })
})

See it in action:

$(function() {
  $('.card-tall').each(function() {
    $(this).append($('<img />', {
      class: 'd-inline-block w-100 h-auto invisible',
      src: $(this).css('backgroundImage').replace('url("', '').replace('")', '')
    }))
  })
})
.card-tall {
  background-size: contain;
  background-repeat: none;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b10170c07101256181b2a38050911120e">[email protected]</a>/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<div class="container">
  <div class="row">
    <div class="col-sm-4">
      <div class="card card-tall" style="background-image:url(https://picsum.photos/200/200)"></div>
    </div>
    <div class="col-sm-4">
      <div class="card card-tall" style="background-image:url(https://picsum.photos/200/300)"></div>
    </div>
    <div class="col-sm-4">
      <div class="card card-tall" style="background-image:url(https://picsum.photos/300/200)"></div>
    </div>
  </div>
</div>

Add the d-md-none class to limit the <img> display behavior to small screens (sm and below).

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

Switching the favicon to utilize the favicon.ico file

After initially adding a favicon to my HTML page, I attempted to change it to a different one. However, the first favicon seems to be stuck and won't move, even after removing the link tag entirely. I created a new favicon (favicon.ico) and tried impl ...

Swapping out DIVs with jQuery

Currently, I am working on a project for a client where I need to create a sortable biography section using jQuery. Initially, I had a setup with just two bios (first person and third person) which was functioning perfectly: $("a#first").click(function() ...

What is the best method for arranging checkboxes in a vertical line alongside a list of items for uniform alignment?

Trying to come up with a solution to include checkboxes for each item in the list, maintaining even vertical alignment. The goal is to have the checkboxes in a straight vertical line rather than a zigzag pattern. Coffee Nestle ...

How come my counter is still at 0 even though I incremented it within the loop?

Within my HTML file, the code snippet below is present: <div id="userCount" class="number count-to" data-from="0" data-to="" data-speed="1000" data-fresh-interval="20"></div> In my Ja ...

Animation will cease once the page is refreshed via Ajax

I'm facing a challenge with a problem that I can't seem to resolve. The issue lies in my use of this plugin for displaying random images. The only step left is to refresh the content within the div. However, every time I attempt to do so, the an ...

Mistake made by the author while using the Google Structured Data Test

While reviewing my website, I encountered an error message stating: "Missing required hCard "author"" http://www.google.com/webmasters/tools/richsnippets?q=http%3A%2F%2Fwww.gamempire.it%2Fcastlestorm-ps-vita%2Frecensione%2F131419 Why is this happening? I ...

Refreshing a div using ajax technology

I am attempting to use Ajax to update an h3 element with the id data. The Ajax call is making a get request to fetch data from an API, but for some reason, the HTML content is not getting updated. This is how the JSON data looks: {ticker: "TEST", Price: 7 ...

Personalized design for the range input in React

I am working on a React component that includes an input range element. I have used some CSS to style it vertically and currently, it looks like this: https://i.stack.imgur.com/WmQP4.png My goal is to customize the appearance of the slider so that it res ...

Alter the color of H3 when clicked and then gently fade it back

Is it possible to create a button on the top of my webpage that scrolls to a specific DIV when clicked, and also have it change the color of an h3 element once it has scrolled to it? This effect is similar to how Facebook highlights notifications. This is ...

Implementing a redirection of Dojo Data grid cell values to a different destination

I am working with a Dojo data grid that contains 10 rows (cells) of values. When the first row is clicked, I need it to redirect to another HTML page and carry along the values from the first row. Can you assist me in achieving this functionality? ...

Reviewing code for a simple form and box using HTML5 and CSS3

I have developed a compact form as part of a larger webpage, proceeding step by step according to the specified requirements. I am wondering if there could have been a more efficient way to code this. Perhaps streamlining the code or utilizing different c ...

When Socket.emit is called, it outputs <span> elements within a well-structured message

Currently working on a small chat application using Node.js, Express.js, and Socket.IO. However, I'm encountering an issue with formatting. Instead of displaying the message content within <span> tags as intended, it is printing out the actual t ...

Determine in Jquery if all the elements in array 2 are being utilized by array 1

Can anyone help me figure out why my array1 has a different length than array2? I've been searching for hours trying to find the mistake in my code. If it's not related to that, could someone kindly point out where I went wrong? function contr ...

use ajax to dynamically append a dropdown menu

Currently working on creating a form that includes a dropdown menu populated with elements from a database. The challenge I'm facing is ensuring that once an element is selected from the dropdown, another one appears dynamically. My goal is to use AJA ...

Retrieve input value in Angular 8 using only the element's ID

Can the value of an input be obtained in Angular 8 with TypeScript if only the element's id is known? ...

Design a big-sized button using Bootstrap framework

Is there a way to design a big, responsive button using Bootstrap? Similar to the example image linked below https://i.sstatic.net/xEBwc.png ...

Enhanced Interactivity: jQuery UI Dialog Button Transforms Position upon Mouse Hover

I am utilizing the jQuery UI dialog feature and implementing buttons using jQuery in the following manner: $("#151").dialog({ autoOpen: false, autoResize: true, buttons: { "OK": function ...

The console correctly detects the value, but is unable to set the innerHTML property of null

I am currently working on a webpage that allows users to sign in and create an account. The issue I'm facing is that when I try to display the user's information, I encounter the error 'Cannot set property 'innerHTML' of null.&apos ...

Steps for making a toggle button with Bootstrap

Initially, I developed a web application using HTML, CSS, and JavaScript. Later on, I was requested to recreate it using Bootstrap as well. While I managed to complete the task successfully, I encountered an issue where toggle buttons in the web app revert ...

Trouble with CSS display in Internet Explorer 8

My website located at this link is working perfectly in IE 10 and IE 11, however, any version lower than that is causing the content to be displayed on the far left of the screen instead of centering it. I have tried tweaking the CSS but can't seem to ...