Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spacing between flex elements?

Tags:

html

css

flexbox

JSFiddle

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|
like image 655
panthro Avatar asked Sep 08 '16 08:09

panthro


People also ask

Can I use gap with Flex?

The gap property is designed for use in grid, flex and multi-column layouts.

What is the space between to items?

space-between : items are evenly distributed in the line; first item is on the start line, last item on the end line. space-around : items are evenly distributed in the line with equal space around them.


1 Answers

Check this out- I used calc to adjust the flex-basis to allow custom margins 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!

like image 146
kukkuz Avatar answered Oct 25 '22 07:10

kukkuz