Reputation: 24061
I have a list displayed with flex:
<ul>
<li></li>
....
ul{
list-style-type: none;
display: flex;
flex-wrap: wrap;
background: gold;
}
li{
flex-basis: 25%;
background:grey;
}
Now I want some space between my li elements, adding margin or padding pushes the elements on to the next line (I want flex wrap for when I have more than 4 elements).
I know the above can be solved with box sizing, but my main problem is that I want spacing between the elements, but with the first and last element to line up to the left and right side of the parent element.
How can this be achieved?
eg.
|li|spacing|li|spacing|li|spacing|li|
Upvotes: 12
Views: 30142
Reputation: 11
Since this is the first google result I want to add this can be accomplished with the new "gap" property:
ul {
gap: 8px;
}
Upvotes: 1
Reputation: 1492
A much simpler solution (in the generic use case):
Say you have 2 elements like below:
You can use the following css to get the same spacing between the elements.
Example:
.elem1 {
display: flex;
flex-wrap: wrap;
margin-left: 8px;
margin-top: 8px;
}
.elem2 {
margin-right: 8px;
margin-bottom: 8px;
}
<div class="elem1">
<div class="elem2">1</div>
<div class="elem2">2</div>
<div class="elem2">3</div>
<div class="elem2">4</div>
</div>
This achieves the same spacing on the outer border, as well as between elements (in the x or y direction) without any extra calculation. While justify-content: space-between
or justify-content: space-around
can have a similar effect, it also centers everything.
React Example (with Material UI)
render() {
return (
<Box display="flex" flexWrap="wrap" ml={1} mt={1} >
{this.service.items().map(element =>
<Box key={element.id} mr={1} mb={1} >
<Card entity={element} />
</Box>
)}
</Box>
)
}
Upvotes: 0
Reputation: 42352
Check this out- I used calc
to adjust the flex-basis
to allow custom margin
s that you can distribute for the ul
(used justify-content: space-between
for distributing that margin).
ul {
list-style-type: none;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
background: gold;
margin: 10px;
padding: 0;
height: 100px;
}
li {
flex-basis: calc(25% - 20px);
background: grey;
}
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
Let me know your feedback on this. Thanks!
Upvotes: 17