Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontal lists in CSS

Tags:

css

What's the best practice for doing a horizontal list in css? Now I know this is a very basic question but the effect I'm looking for is in a website like this: http://www.frontend2011.com/.

If you scroll down to the video portion with the 4 column lists, you'll see a good use of it. But if I give something like float: left and margin-left: #px; in the CSS, my last list item always falls to the next row before not even getting close to the edge of the div box model.

I've heard it's because of the box model and the border/padding/margin but what's the best way to get past this? I would like the lists to touch the right and left sides of the div but this seems impossible for me.

like image 354
Nerdysyntax Avatar asked Mar 02 '12 16:03

Nerdysyntax


2 Answers

this could be a good use of box-sizing property (supported by all browser, IE8 included): given an unordered list (and assuming list-items all with the same height) you can assign this style to every <li>:

li {
   -webkit-box-sizing: border-box;
   -moz-box-sizing: border-box;
   box-sizing: border-box;

   float   : left;
   width   : 25%;
   padding : 15px; /* this will be applied internally, due to 
                      box-sizing property */

}

then if you want to force a clearing after every 4thli, just add

li:nth-child(4n) { 
   clear : left; 
}

otherwise, if you can't be sure that every <li> have always the same height then use inline-block position instead of float.

like image 183
Fabrizio Calderan Avatar answered Nov 05 '22 12:11

Fabrizio Calderan


There are several ways to display a list horizontally.

1) You can set the li:s to display: inline, inline elements' width, height and padding can not be styled the same way block elements can so if you want backgrounds or borders you should use:

2) display: inline-block displays the li:s on one line while keeping the features of a block element, inline-block works in most browsers but you may need to use *display: inline for IE7 and below. inline and inline-block elements are affected by line-height and font-size and you may get unwanted gaps between your menu items, you can easily solve this by setting the font-size to 0 on the ul and setting it back to normal in the li:s.

3) Thirdly you can use display: block together with float: left, problem with float is that it can't be centered like display: inline-block easily can with text-align: center and you have to remember to clear the parent element (overflow: hidden on the ul is enough)

4) If you need your list to span the entire width of its parent, the easiest thing you can do is use display: table; width: 100% on the ul and display: table-cell on the li:s, making the ul behave just like a table

like image 2
powerbuoy Avatar answered Nov 05 '22 11:11

powerbuoy