'css align element to have the same space between them [duplicate]
So I have the following scenario where i have a list (can be anything else, i don't really care) that has to have the same spacing between them(green lines) and the same spacing at the beginning and end (red arrows). All this without the container having a fixed position, so if I resize and/add more elements they should still span properly.
I have created a pen with what i "achieved" so far.
This is my code so far:
ul{
width: 90%;
border: 1px solid black;
}
li{
display: inline-block;
margin: 0 100px;
border:1px solid orangered;
}
li:first-child{
margin-left: 20px;
}
li:last-child{
margin-right: 20px;
}
I have also tried with display:grid, they fit properly in the red margins, but don't span equal spacing in between them.
Can this be achieved without the use of JS?
Solution 1:[1]
You can use display: flex and justify-content: space-around on the ulelement
ul{
width: 100%;
justify-content: space-around;
display: flex;
list-style: none;
padding: 0;
}
li{
border: 1px solid red;
padding: 0;
}
<ul>
<li>list element 1</li>
<li>element 2</li>
<li>e4</li>
<li>list e5</li>
</ul>
Solution 2:[2]
ul{
padding-left: 20px;
padding-right: 20px;
}
li{
display: inline-block;
padding-left: 100px;
padding-right: 100px;
}
li:first-child{
padding-left: 0px;
}
li:last-child{
padding-right: 0px;
}
Try it :)
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 | |
| Solution 2 |

