-1

Here is the playground :

.container {
  width: 500px;
  display: flex;
  flex-flow: row wrap;
  align-items: flex-start;
  align-content: flex-start;
  justify-content: flex-start;
  justify-items: flex-start;
  gap: 1rem;
  padding: 1rem;
  box-sizing: border-box;
  border: 1px solid salmon;
}



.item {
  flex: 1 1 auto;
  min-width: 50px;
  height: 6rem;
  padding: 1rem;
  box-sizing: border-box;
  background-color: teal;
  border-radius: 0.4rem;
  display: grid;
  place-items: center;
  font-size: 1.25rem;
  line-height: 1.5rem;
  text-align: center;
  cursor: pointer;
}
<div class="container">

  <div class="item">Some content</div>
  <div class="item">Some content</div>
  <div class="item">Some content</div>
  <div class="item">Some content in the item</div>

</div>

As you can see the last item is taking the remaning space, I would like it not to, and instead take the space required by the text. How should I proceed ?

I am aware I can use grid layout for this, but I would like to stay on flex layout.

MGX
  • 2,534
  • 2
  • 14
  • I have experimented & played around and this is the [result](https://jsfiddle.net/row6mz15/91/). I believe you have to set a width on the individual items themselves. – Abdulrahman Ali Feb 06 '23 at 14:51
  • Setting a width on a flexed element is everything I don't want to do, and so should you ! – MGX Feb 06 '23 at 16:32

2 Answers2

2

This is the last-child implementation suggested by the other answer. It does what you literally ask for in your question, but I'm not sure it's what you are really going after.

.container {
  width: 500px;
  display: flex;
  flex-flow: row wrap;
  align-items: flex-start;
  align-content: flex-start;
  justify-content: flex-start;
  justify-items: flex-start;
  gap: 1rem;
  padding: 1rem;
  box-sizing: border-box;
  border: 1px solid salmon;
}

.item {
  flex: 1 1 auto;
  min-width: 50px;
  height: 6rem;
  padding: 1rem;
  box-sizing: border-box;
  background-color: teal;
  border-radius: 0.4rem;
  display: grid;
  place-items: center;
  font-size: 1.25rem;
  line-height: 1.5rem;
  text-align: center;
  cursor: pointer;
}

.item:last-child {
  flex: 0 0 auto;
}
<div class="container">

  <div class="item">Some content</div>
  <div class="item">Some content</div>
  <div class="item">Some content</div>
  <div class="item">Some content in the item</div>

</div>
dgrogan
  • 2,587
  • 1
  • 17
  • 21
1

You could always use :last-child, here is the link with article about this, so you can read through it and try to implement it on your own.

  • This is an example, I don't know how many children there can be, one being the minimum – MGX Feb 06 '23 at 16:32
  • Here are two articles for you to read if you want to know more about it. [First](https://css-tricks.com/almanac/selectors/l/last-child/) and [second](https://www.scaler.com/topics/last-child-css/) article for you. I hope it will be useful to read through it. – Cvijan Djukanovic Feb 07 '23 at 08:17