Search code examples
csslistwidthcss-position

How to make responsive layout with floated list-items?


I'm making a responsive list with floated <li>'s, where I want the list to stay with three columns. However, when resizing the window the floated items are pushed – as with fixed items – into two columns, instead of resizing. Here's an example of my code:

#list {
  position: relative;
  width: 100%;
  display: block;
}

#list li {
  position: relative;
  width: 27%;
  float: left;
  margin: 2% 2% 0 0;
  display: block;
}
<ul id="list">
  <li>item1</li>
  <li>item1</li>
  <li>item1</li>
  <li>item1</li>
  <li>item1</li>
  <li>item1</li>
<ul>


Solution

  • Problem with % and maring/padding in N-column layouts is pixels rounding.

    If you define 2%+2%+2% padding, without rounding it could be 20.4px+20.4px+20.4px=61.2px. But with rounding it will give 20px+20px+20px=60px.

    Also different browsers may round pixels differently. Suppose that 2% is equal to 20.7px. Some browsers may round it to 20px, others to 21px.


    You can use inner element if you need to combine % and some margin/padding. Is is best what I've found so far for cross-browser solution:

    HTML:

       <ul id="list">
           <li><span>item1</span></li>
           <li><span>item1</span></li>
           <li><span>item1</span></li>
           <li><span>item1</span></li>
        <ul>
    

    css:

    #list{
        position: relative;
        width: 100%;
        display: block;
    }
    
    #list li {
        width: 33.3%; /* nice 3 columns */
        float: left;
        padding: 0; /* should have zero paddng/margin */
        margin: 0;
    }
    
    #list li > span {
     margin: 6% 6% 0 0; /* now margins are specified relative to outer <li> width */
     display: block;
    }
    

    Aditionally you can specify two columns for lower screen sizes:

    @media only screen and (max-width: 800px) {
       #list li {
            width: 49.9%;
       }
    }