Home > Net >  How to set column width to content width in CSS Grid
How to set column width to content width in CSS Grid

Time:09-29

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?

CodePudding user response:

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>

CodePudding user response:

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 >
  <li>Item11111</li>
  <li>Content11111</li>
  <li>Item</li>
  <li>Content</li>
</ul>

CodePudding user response:

You can do something tricky thing like this :

image of grid

Create a grid with 3 columns and two rows.

I'll probably do something like that :

.grid {
  display: grid; 
  grid-template-columns: 1.4fr 0.4fr 1.2fr; 
  grid-template-rows: 1fr 1fr; 
  gap: 10px 10px; 
  grid-template-areas: 
    "content1 content1 item2"
    "item1 content2 content2"; 
}

.content1 {
 grid-area: content1;
}

.content2 {
 grid-area: content2;
}

.item1 {
 grid-area: item1;
}

.item2 {
 grid-area: item2;
}

Hope it will help you!

  • Related