Search code examples
htmlcsswidthcenter

Center float container without width


I have this HTML:

<div id="container">
    <article></article>
    <article></article>
    <article></article>
    <article></article>
    <article></article>
</div>

and this CSS:

#container {
    overflow: hidden
}

article {
    float:left;
    height: 200px;
    width: 200px;
    background-color: red;
    margin: 5px;
}

​ ​I want to center the #container without specifying a width. Is it possible?
Here is the Fiddle.

Edit: I need the width of the #container to change to fit the articles. If the body is 450px width then there will be two articles per row, so the width of the container should be 400px aprox. If the body is 1100px width then ther will be five articles per row, so the width of the container should be 1000px aprox.


Solution

  • After considering several options, I found that using media queries is the simpler way to do it.

    In this case it will be something like this:

    @media (max-width: 420px) {
        #container {
            width: 210px;
        }
    }
    
    @media (min-width: 420px) and (max-width: 630px) {
        #container {
            width: 420px;
        }
    }
    
    @media (min-width: 630px){
        #container {
            width: 630px;
        }
    }
    

    Here is the fiddle.