Reputation: 1047
A separate question to find the final solution which we almost have found here (many thanks to everyone who answered there).
I have an unordered list. The list can have any number of items inside, it's dynamic. The list is stylized in such a way that there are 3 list items per row (each item takes 1/3 of the parent width).
Solutions proposed in another question I mentioned above has 2 problems:
justify-content: flex;
, when we have 5 items in the list, 4th and 5th items jump in the opposite corners, while they have to stick to the left.This is what I need. This way the list should look if we have 3 list items:
And this is an illustration to clarify what should happen if we have 4 or more items in the list:
And this is the code I tried (thanks for the help in the other post):
.parent{
display: flex;
flex-wrap: wrap;
width: 100%;
height: 100px;
gap: 20px;
box-sizing: border-box;
justify-content: space-between;
background-color: lightgreen;
}
.child{
flex-basis: 30%;
background-color: blue;
color: white;
display: flex;
justify-content: center;
align-items: center;
}
<div class="parent">
<div class="child"> <span>1</span> </div>
<div class="child"> <span>2</span> </div>
<div class="child"> <span>3</span> </div>
<div class="child"> <span>4</span> </div>
<div class="child"> <span>5</span> </div>
</div>
Upvotes: 0
Views: 568
Reputation: 631
Use :after
pseudo element to simulate an invisible child div so the alignment of the items is fixed to left. And media queries for the responsive. Check the snippet to get some idea.
.parent {
display: flex;
flex-wrap: wrap;
width: 100%;
height: 100%;
gap: 20px;
box-sizing: border-box;
justify-content: space-between;
background-color: lightgreen;
}
.parent::after {
content: "";
width: 30%;
height: 0;
}
.child {
flex-basis: 30%;
background-color: blue;
color: white;
display: flex;
justify-content: center;
align-items: center;
}
@media only screen and (max-width : 1024px) {
/* for tablet */
.parent::after {
width: 46%;
}
.child {
flex-basis: 46%;
}
}
@media only screen and (max-width : 768px) {
/* for mobile */
.parent::after {
display: none;
}
.child {
flex-basis: 100%;
}
}
<div class="parent">
<div class="child"> <span>1</span> </div>
<div class="child"> <span>2</span> </div>
<div class="child"> <span>3</span> </div>
<div class="child"> <span>4</span> </div>
<div class="child"> <span>5</span> </div>
</div>
Upvotes: 1