Home > Net >  How to make every grid item the same width/height when one of them has an image child?
How to make every grid item the same width/height when one of them has an image child?

Time:06-21

I've been trying to get familiar with grid while making the sidebar, and I encountered the problem where my grid items/children aren't equal to each-other in height even though they're supposed to be the same size.

* {
  margin: 0;
  padding: 0;
}

.mainContainer {
  height: 500px;
  gap: 30px;
  display: grid;
  grid-row-template: repeat(auto-fill, 1fr);
  background-color: black;
  color: white;
  justify-items: center;
  align-items: start;
}

.mainContainer div {
  display: grid;
  align-content: center;
  justify-content: center;
  width: 60%;
  border: 1px solid yellow;
  height: 60%;
  border-radius: 10px;
}

.mainContainer img {
  height: 50%;
  width: 100%;
  object-fit: contain;
}
<div >
  <div> <img src="https://pbs.twimg.com/profile_images/1455185376876826625/s1AjSxph_400x400.jpg"> </div>
  <div> Box 1 </div>
  <div> Box 2 </div>
  <div> Box 3 </div>
</div>

CodePudding user response:

Focusing on the image

.mainContainer img{
  height: 30px; // set it to any size
  object-fit: contain;
}

I think you should use px instead of %

enter image description here

enter image description here

CodePudding user response:

You can use this, it is done without grid, but with a flex-column.

    * {
      margin: 0;
      padding: 0;
    }

    .mainContainer{
      height: 500px;
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 30px;
      background-color: black;
      color: white;
    }
    
    .mainContainer > * {
      height: 25%;
      width: 60%;
      border: 1px solid yellow;
      /* center image / text in children boxes */
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .mainContainer img {
      object-fit: contain;
    }
  • Related