Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I distribute items horizontally with CSS? [duplicate]

Tags:

I would like to distribute a few list items horizontally on a bar, and I want to make the code modular so it automatically adjusts the space between items when I insert more.

I want the first item on the leftmost side, and the right item on the rightmost side, and the rest distributed in between. They all have equal space between each other. Think of separating a line segment into several pieces, the items would mark the points of separation, as well as the head/tail of the original line segment.

I tried several solutions and found some online, but they don't do what I want. They just centre everything more like putting each item in the middle of each line pieces according to my previous analogy.

Can someone please provide a nice solution in CSS?

like image 766
Xavier_Ex Avatar asked Nov 22 '12 03:11

Xavier_Ex


People also ask

How do you arrange things horizontally in CSS?

To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.

How do I make an object equally space in CSS?

There are two methods to create equally spaced “div” element using CSS. Approach: We can make a container and then set the display property to flex. It creates a Flexbox. Now we can apply flexbox properties to the items of the container.

How do I put divs next to each other horizontally?

With CSS properties, you can easily put two <div> next to each other in HTML. Use the CSS property float to achieve this. With that, add height:100px and set margin.


1 Answers

You can do what you are after using inline-block, pseudo-elements and text-align: justify;, but it will only work in IE8 and above.

Here is the code:

<!-- HTML -->  <ul>     <li>List Item 1</li>     <li>List Item 2</li>     <li>List Item 3</li>     <li>List Item 4</li> </ul> 

​ /* CSS */  ul {     text-align: justify; } ul:after {     content: '';     display: inline-block;     width: 100%; } ul:before {     content: '';     display: block;     margin-top: -1.25em; } li {     display: inline-block;     margin-right: -.25em;     position: relative;     top: 1.25em; } 

Live demo: http://jsfiddle.net/joshnh/UX9GU/ ​

like image 104
joshnh Avatar answered Sep 30 '22 17:09

joshnh