Search code examples
htmlcsscss-grid

CSS Grid Columns limit card width based on background image


I have a dynamic CSS grid layout of a bunch of cards right now which scales to fit the width of the screen

5x card layout

However, when there are only a couple of cards, the cards stretch out to fill the whole screen because of the 1fr property, and I would like to limit them only as wide as their background image is or scale the image to the size of the card, or something along those lines.

x2 stretched cards

Here is the code for the CSS grid

.resources-container {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr));
  grid-auto-rows: auto;
  grid-gap: 1rem;
}

I was able to achieve somewhat the desired result by doing

grid-template-columns: repeat(auto-fit, minmax(15rem, auto));

but it still stretched past the limit.

Here is the code for the card (condensed)

<template>
  <div class="card">
    <div class="sidebar">
      <div class="votes-container"></div>
      <div class="comments-container"></div>
    </div>
    <img class="card-image" :src="content.image" />
    <div class="card-contents">
      <h1 class="title">{{ content.title }}</h1>
      <h2 class="subtitle">{{ content.subtitle }}</h2>
    </div>
  </div>
</template>


<style lang="scss" scoped>
.card {
  min-width: 15rem;
  max-width: 100%;
  height: 300px;

  margin-right: 0.5rem;
  margin-left: 0.5rem;
  margin-bottom: 0;

  flex: 0 0 auto;

  display: block;
  position: relative;
  overflow: hidden;

  text-align: left;

  img {
    object-fit: cover;
    height: 100%;
    background-position-x: center;
  }

  .card-contents {
    position: absolute;
    bottom: 0;
    left: 0;
  }

  .sidebar {
    display: flex;
    flex-direction: column;
    align-items: center;

    position: absolute;
    right: 0;

    width: 2rem;
    height: 100%;
  }
}

Solution

  • I was able to scale the background image by adding a width: 100% tag on top of the existing height: 100% tag, which prevents the ugly background scaling shown in the original images.

    img {
      object-fit: cover;
      height: 100%;
      width: 100%;
      background-position-x: center;
    }
    

    Better looking 2x stretched images