0

I have a multiple column CSS Grid defined with repeat(6, 1fr) but with only one or two columns defined. It seems justifying center or space-between does not work in this case, probably because the grid already knows it has 6 equal width columns so there is nothing to justify?

.grid {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    grid-template-rows: 3em;
    grid-gap: 1rem;
    /*justify-items: center; horizontally centers column content */
    /*align-items: center; vertically centers column content */
}

.grid > div {
  background-color: yellow;
}

.grid > div:first-child {
  background-color: orange;
}
<div class="grid">
   <div>content1</div>
   <div>content2</div>
</div>

2
  • 1
    probably because the grid already knows it has 6 equal width columns so there is nothing to justify? --> you got it. Flexbox is what you need here Commented Mar 10, 2021 at 11:59
  • I know that :) However, the premise was that if you are obliged to use a CSS Grid layout and you encounter this situation, is there a way to do it? Other than just rewrite to flexbox. Commented Mar 10, 2021 at 12:07

1 Answer 1

1

If you will have only one row you can do the following otherwise use flexbox:

.grid {
  display: grid;
  grid-auto-columns: calc((100% - 5rem)/6); 
  grid-auto-flow: column;
  grid-template-rows: 3em;
  grid-gap: 1rem;
  justify-content: center;
  border: 1px solid;
}

.grid>div {
  background-color: yellow;
}

.grid>div:first-child {
  background-color: orange;
}
<div class="grid">
  <div>content1</div>
  <div>content2</div>
</div>

<div class="grid">
  <div>content1</div>
  <div>content2</div>
  <div>content3</div>
</div>

<div class="grid" style="justify-content: space-between;">
  <div>content1</div>
  <div>content2</div>
</div>

<div class="grid" style="justify-content: space-between;">
  <div>content1</div>
  <div>content2</div>
  <div>content3</div>
</div>

Sign up to request clarification or add additional context in comments.

4 Comments

I see the solution but can you explain what is happening with refactoring from the grid-template-columns: repeat(6, 1fr) to your set of grid-auto-... rules? Also, why would this now work in multiple rows layout?
@lavirius using your rule you will always have 6 columns, with mine the number of column will depend on the element (I didn't define any number of columns)
@lavirius it won't work with mutiple rows because I am using a column flow so fixed number of row and variable number of column (in my case one row)
I would vote your answer if it would be more elaborately explained :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.