1

I basically have the question as this one, except that every answer seems to think the OP wants the container .row element to grow to effectively have width: 100% (which they never state that they want, but nor have they corrected the assumption of any of the answers). This question also seems to be similar, if not the same, as mine, but has no accepted answer and the upvoted answer didn't work for me.

I'm trying to achieve sibling elements in a row where each sibling's width is the width of the widest sibling (auto-fit to its contents), but crucially where the parent row element itself does not grow to 100% of its own parent but rather grows only to the total combined width of its children.

I've tried dozens of suggestions without any success. Here's what I consider the closest I've managed:

.full-width-banner {
  width: 100%;
  background-color: #aaa;
  padding: 5px;
  margin-bottom: 5px;
}

.days-of-week {
  display: grid;
  grid-auto-columns: max-content;
}

.item {
  padding: 2px;
  border: 1px solid #ccc;
}
<div class="container">
  <div class="full-width-banner">Hi there!</div>
  <div class="days-of-week">
    <div class="item">Monday</div>
    <div class="item">Tuesday</div>
    <div class="item">Wednesday</div>
    <div class="item">Thurdsday</div>
    <div class="item">Friday</div>
    <div class="item">Saturday</div>
    <div class="item">Sunday</div>
  </div>
</div>

This does set all of the siblings - the days of the week - to have equal widths as required, but it stacks them rather than showing them inline. I thought adding grid-auto-flow: column; to the .days-of-week element might fix it, but whilst that does cause the days to be displayed inline, their widths revert to match their respective contents.

So, using CSS grid, how can I get the days of the week elements to all have equal widths no greater than the natural width (as prescribed by its content) of the widest element?

Charles Lavalard
  • 2,061
  • 6
  • 26
Philip Stratford
  • 4,513
  • 4
  • 45
  • 71

1 Answers1

1

You need to do like below:

.full-width-banner {
  background-color: #aaa;
  padding: 5px;
  margin-bottom: 5px;
}

.days-of-week {
  display: inline-grid; /* inline grid */
  grid-auto-columns: 1fr; /* all of them the same size */
  grid-auto-flow:column; /* a column flow */
}

.item {
  padding: 2px;
  border: 1px solid #ccc;
}
<div class="container">
  <div class="full-width-banner">Hi there!</div>
  <div class="days-of-week">
  <div class="item">Monday</div>
  <div class="item">Tuesday</div>
  <div class="item">Wednesday</div>
  <div class="item">Thurdsday</div>
  <div class="item">Friday</div>
  <div class="item">Saturday</div>
  <div class="item">Sunday</div>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415