When it comes to centering flex items, using justify-content: center;
may not always be the best approach, especially when resizing. I recommend exploring alternative methods like setting width: fit-content
and margin: auto;
to achieve a centered layout. Another option is to apply max-width
on the flex parent or utilize space-between
instead of a static gap
for better responsiveness.
Review the code snippet below:
.flexbox {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
width: fit-content; /* allows margin auto to center */
margin: auto;
}
.flex-item {
width: calc(100%/3.1); /* .1 for spacing paired with space-between for smaller screens */
}
img {
max-width: 100%; /* responsive images */
}
<div class="flexbox">
<div class="flex-item">
<img src="https://dummyimage.com/300/000/fff">
<h6> Hello World </h6>
</div>
<div class="flex-item">
<img src="https://dummyimage.com/300/000/fff">
<h6> Hello World </h6>
</div>
<div class="flex-item">
<img src="https://dummyimage.com/300/000/fff">
<h6> Hello World </h6>
</div>
<div class="flex-item">
<img src="https://dummyimage.com/300/000/fff">
<h6> Hello World </h6>
</div>
</div>