Alopwer
Alopwer

Reputation: 630

How to make first and last element of a grid different sizes from the other elements?

I have a grid

<div class="grid">
  // a lot of divs
</div>

css

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(90px, 1fr));
}

I need to make the highlighted elements of max-width: 45px. I've tried grid-template-columns: 45 px repeat(auto-fill, minmax(90px, 1fr)) 45px but what it does is making first and last column 45px width (but I need the elements). Setting max-width doesn't help, because the first element's line is cut in twice. How can I achieve that? I'm not using flexbox as it can't achieve what I want. enter image description here

Upvotes: 1

Views: 6797

Answers (2)

colourCoder
colourCoder

Reputation: 1452

A similar answer incorporating your additional question on centering the elements on page:

elements centered on page

Main points:

  • replacing 'auto-fill' with auto-fit
  • using max-content instead of '1fr'
  • adding justify-content: center

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(45px, max-content));
  justify-content: center;
   
}
.grid-item {
  border: 1px solid blue;
  grid-column: span 2;
}

.grid-item:first-child, .grid-item:last-child {
  grid-column: span 1;
}
<div class="grid-container">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">4</div>
  <div class="grid-item">5</div>
  <div class="grid-item">6</div>
  <div class="grid-item">7</div>
  <div class="grid-item">8</div>
</div>

Upvotes: 3

mcernak
mcernak

Reputation: 9130

You can make all columns 45px wide and then have all items except the first and the last item span two columns, e.g.:

enter image description here

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(45px, 1fr));
}
.grid div {
  border: 1px solid blue;
}

.grid div {
  grid-column: span 2;
}
.grid div:first-child, .grid div:last-child {
  grid-column: span 1;
}
<div class="grid" style='max-width:500px'>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
</div>

Upvotes: 4

Related Questions