Home > OS >  CSS Grid Columns limit card width based on background image
CSS Grid Columns limit card width based on background image

Time:09-04

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 >
    <div >
      <div ></div>
      <div ></div>
    </div>
    <img  :src="content.image" />
    <div >
      <h1 >{{ content.title }}</h1>
      <h2 >{{ 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%;
  }
}

CodePudding user response:

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

CodePudding user response:

If I'm understanding your question correctly, something like this will work (see modified repeat option on grid-template-columns):

.wrapper { 
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 1rem;
  margin-bottom: 4rem;
}

.card { 
  border: 1px solid red;
}
<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
  <div >5</div>
</div>

<div >
  <div >1</div>
  <div >2</div>
</div>

  • Related