1

I have a list of blocks, that I want to place in two rows, now I use grid:

li:nth-of-type(2n) {
  grid-row-start: 2;
}

li:nth-of-type(2n + 1) {
  grid-row-start: 1;
}
<ul>
<li>Item</li>
<li>Item</li>
<li>Item1111</li>
<li>content content</li>
</ul>

You can see, what I get:

current result

I want to set width of every grid cell to width of its content, like on the pic desired result

Is it even possible?

Zach Jensz
  • 3,650
  • 5
  • 15
  • 30
  • 2
    Nope. Grid columns can't adapt to the content. And a flexbox solution would not align rows the way you want. – Zach Jensz Sep 28 '22 at 12:46
  • Oh I just read your question again. You actually want the second image yeah that's possible. I'll write a flexbox solution – Zach Jensz Sep 28 '22 at 12:48
  • Might be more of a css masonry question: https://stackoverflow.com/questions/44377343/css-only-masonry-layout – Pete Sep 28 '22 at 13:22

2 Answers2

1

If you don't need the rows to align you can try flexbox instead of grid:

ul {
  display: flex;
  flex-flow: row wrap;
  list-style: none;
  padding: none;
  max-width: 9rem;
}

li {
  padding: 0.1em;
  border: 1px solid currentColor;
}
<ul>
  <li>Content 1</li>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>content 2</li>
</ul>
Zach Jensz
  • 3,650
  • 5
  • 15
  • 30
-1

set grid rows and columns to auto grid-template-rows: auto auto; grid-template-columns: auto auto;

set width of the li's width: max-content;

.grid-container {
  display: grid;
  grid-template-rows: auto auto;
  grid-template-columns: auto auto;
  width: 250px;
  gap:10px;
}

li {
  list-style: none;
  padding: 1rem;
  background-color: #EDF6FF;
  border-radius:10px;
  width: max-content;
  color:#2E4665;
}
<ul class="grid-container">
  <li>Item11111</li>
  <li>Content11111</li>
  <li>Item</li>
  <li>Content</li>
</ul>
UmairFarooq
  • 1,269
  • 1
  • 3
  • 8
  • The question is - perhaps - a little ambiguous, but I think OP wants the result shown in the last picture, your answer seems to reproduce the result that they already get, and don't want. But - until OP comments either way - I'm not entirely certain of that. – David Thomas Sep 28 '22 at 12:56
  • oh.no worries ill delete once confirmed – UmairFarooq Sep 28 '22 at 12:57