Search code examples
cssfluid-layoutliquid-layout

Fluid layout with CSS


I have a page that has 10 divs acting as big buttons that are displaying in 2 rows of 5 but I would like it so that if the page is resized or it is opened on a device with a smaller screen the layout of the buttons changes automatically but I'm not sure how to go about this.

Where should I start looking or does anyone know any good tutorials that could help me achieve this?

Thanks


Solution

  • The name for that is Reactive (or Responsive) Design. You can find a decent intro to it here: http://netuncovered.com/2011/05/reactive-web-design/

    It all comes down to @media queries in the CSS to determine the size of the window you're dealing with, and changing styles accordingly. Something like:

    @media screen and (min-width:768px)
    {
        .my_div { width: 200px; }
    }
    @media screen and (min-width:1024px)
    {
        .my_div { width: 300px; }
    }
    

    This example gives you different sizes for the divs based on the window size. You can do the same w/ positioning or any other CSS rule based on the size of the screen using @media queries.

    For the specific question of how do you change the number of items in a row, let's say you have the following HTML:

    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="clear3"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="clear5"></div>
    <div class="item"></div>
    <div class="clear3"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="clear3"></div>
    <div class="item"></div>
    

    You can specify, depending on the size of the viewport, when the class .clear3 or .clear5 will actually clear floats. Something like:

    .item { float: left; width: 200px; }
    @media screen and (min-width:768px)
    {
        .clear3 { clear: both; }
        .clear5 { clear: none; }
    }
    @media screen and (min-width:1024px)
    {
        .clear3 { clear: none; }
        .clear5 { clear: both; }
    }
    

    That will change the number of divs per row of .item divs you have, based on the size of the screen. I think. I didn't really test it.