Dave Kiss
Dave Kiss

Reputation: 10485

Center container and make width equal to its floated contents

This should be a basic css question, but as we all know sometimes it can be a tricky language.

<div id="main">    
    <div id="container">
        <div class="item">
        <div class="item">
        <div class="item">
        <div class="item">
        <div class="item">
        <div class="item">
    </div>
</div>

#main {clear: both; margin: 20px auto; max-width: 100%; width: 1000px;}
#container {clear: both; margin: 0 auto; max-width: 832px;}
.item {width: 208px; float: left;}

By default, there are 4 .items in a row. When I resize my browser window to smaller than 832px wide, the .items jump down to fit 3 in a row.

How do I center the 3 items within the #container or make the #container width equal to the width of its floated contents and center the #container in the #main?

mockup

Upvotes: 1

Views: 1289

Answers (1)

Nathan Arthur
Nathan Arthur

Reputation: 9096

I believe this is more or less what you want:

http://jsfiddle.net/L3JVe/17/

It was a simple fix. I set your .items to display:inline-block; and your #container to text-align:center;.

Your new CSS will look something like this:

#main {
    clear: both;
    margin: 20px auto;
    max-width: 100%;
    width: 1000px;
}

#container {
    clear: both;
    margin: 0 auto;
    max-width: 832px;
    text-align:center; /*New*/
}

.item {
    width: 208px; /*May need to adjust*/
    display:inline-block; /*New*/
}​​​​​​​

Also, you'll need to remove all space between the items in the HTML to avoid space appearing between the rendered items. (Thanks, @thirtydot!)

Upvotes: 2

Related Questions