'How to limit the amount of items per row in a flexbox without stretching them using flex-basis?
I am trying to limit the amount of items I have in a flexbox row, and the solution I see the most is using flex-basis, but that causes the elements to stretch, which I don't want, because the elements are links in the form of images, and the stretching causes the link area to be bigger than the image. Is there a way to do this? Here is my HTML and CSS:
HTML:
<div class="spnsr-main">
<h1 id="spnsr-title">Thank You To Our Sponsors</h1>
<div class="spnsrs">
<a class="spnsr-link" href="link" target="_blank"><img class="spnsr" src="../assets/sponsors/spnsr1.png"></a>
<a class="spnsr-link" href="link" target="_blank"><img class="spnsr" src="../assets/sponsors/spnsr2.png"></a>
<a class="spnsr-link" href="link" target="_blank"><img class="spnsr" src="../assets/sponsors/spnsr3.png"></a>
<a class="spnsr-link" href="link" target="_blank"><img class="spnsr" src="../assets/sponsors/spnsr4.png"></a>
<a class="spnsr-link" href="link" target="_blank"><img class="spnsr" src="../assets/sponsors/spnsr5.png"></a>
</div>
</div>
CSS:
.spnsrs {
display:flex;
justify-content:center;
flex-wrap:wrap;
gap:150px 0px;
}
.spnsr {
max-width:350px;
}
.spnsr-link {
text-align:center;
flex-basis:34%;
}
Solution 1:[1]
You can use min-content for your max-width to make the width of the a's or the .spnsr-link class take the minimum width of it's content. See the snippet below:
.spnsrs {
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: .5rem;
}
.spnsr {
max-width: 350px;
}
.spnsr-link {
text-align: center;
max-width: min-content;
}
<div class="spnsr-main">
<h1 id="spnsr-title">Thank You To Our Sponsors</h1>
<div class="spnsrs">
<a class="spnsr-link" href="link" target="_blank"><img class="spnsr" src="https://images.pexels.com/photos/5754453/pexels-photo-5754453.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"></a>
<a class="spnsr-link" href="link" target="_blank"><img class="spnsr" src="https://images.pexels.com/photos/5754453/pexels-photo-5754453.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"></a>
<a class="spnsr-link" href="link" target="_blank"><img class="spnsr" src="https://images.pexels.com/photos/5754453/pexels-photo-5754453.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"></a>
<a class="spnsr-link" href="link" target="_blank"><img class="spnsr" src="https://images.pexels.com/photos/5754453/pexels-photo-5754453.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"></a>
<a class="spnsr-link" href="link" target="_blank"><img class="spnsr" src="https://images.pexels.com/photos/5754453/pexels-photo-5754453.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"></a>
</div>
</div>
More on min-content here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yong |
