'CSS Flexbox Align Itens 2 itens per rows but last row only one item [duplicate]
I'm trying to align itens using Flexbox.
There are 2 "cards" per row and I need to align in center to fit in different devices resolutions (mobile) but the last card need to be on start.
Tried to use align-self: start but no success.
Code:
.parent {
display: flex;
flex-wrap: wrap;
padding: 24px 20px;
justify-content: center;
gap: 16px;
}
.parent > .card {
height: 220px;
width: 152px;
}
Solution 1:[1]
You could wrap your parent container in another div, and set it to justify-content:center. In this way your layout would remain undisturbed.
Here is the CSS:
.new-parent{
display:flex;
flex-direction:row;
justify-content: center;
}
.parent {
display: flex;
flex-wrap: wrap;
padding: 24px 20px;
justify-content: flex-start;
gap: 16px;
}
.parent > .card {
height: 220px;
width: 152px;
}
Solution 2:[2]
Here is an example with the implementation of the grid system which I think would be more appropriate in your case.
However with by using css grid you limit yourself to having only 2 cards per row.
If you want to change the number of cards per row depending on the screen size, you will have to implement it by changing the grid-template-columns property and using media-queries.
.parent {
display: flex;
justify-content: center;
padding: 1rem;
}
.card-list {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
.card {
height: 220px;
width: 152px;
border: 2px solid black;
}
<div class="parent">
<div class="card-list">
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
</div>
</div>
This is a good ressource to learn more about css grid: www.cssgridgarden.com
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 | Aadhit Shanmugam |
| Solution 2 | SamiElk |

