Home > Net >  justify-content does not work for css grid
justify-content does not work for css grid

Time:05-26

Why justify-content: space-between doesnt work in this case? I want to push the last item to the right edge and center the middle one.

div{
  background: lightblue;
  width: 8rem;
  height: 8rem;
}

main{
  margin: 2rem auto;
  width: 80%;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 5rem 0rem;
  background: yellow;
  justify-content: space-between;
  
}
<main>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</main>

CodePudding user response:

You're almost there, but instead of using fractional unit fr, you should use a fixed size 8rem (aligned with your box size).

fr has been stretching your grid box, so that's why you cannot apply justify-content without spare space.

div{
  background: lightblue;
  width: 8rem;
  height: 8rem;
}

main{
  margin: 2rem auto;
  width: 80%;
  display: grid;
  grid-template-columns: repeat(3, 8rem); /*Modify 1fr to 8rem*/
  gap: 5rem 0rem;
  background: yellow;
  justify-content: space-between;
  
}
<main>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</main>

CodePudding user response:

div{
  background: lightblue;
  padding: 20px 0;
}

main{

  display: grid;
  grid-template-columns: 50px 50px 50px; /*Make the grid smaller than the container*/
  gap: 5rem 0rem;
  background: yellow;
  justify-content: space-between;
  
}
<main>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</main>

//you must use percent not absolute

  • Related