user2575265
user2575265

Reputation: 13

Center a non floating element inside an element having floated elements

I'm having issues with aligning some elements inside a nav bar.

Here's an example on jsfiddle: http://jsfiddle.net/flobar/b7nzR/

Here's the html:

<div id="nav">
    <div id="menu">Menu</div>
    <div id="logo">Logo</div>
    <div id="settings">Settings</div>
</div>

Here's the css:

#nav {
    height: 60px;
    border: 1px solid #ccc;    
}

#menu {
    width: 70px;
    height: 30px;
    margin-top: 15px;
    float: left;
    background: #ccc;
}

#logo {
    width: 200px;
    height: 30px;
    margin: 15px auto 0 auto;
    background: #ccc;
}

#settings {
    width: 70px;
    height: 30px;
    margin-top: 15px;
    float: right;
    background: #ccc;
}

The issue is that the far right block is being pushed down by the center block, but I'm not sure why.

Can anyone help please.

Upvotes: 1

Views: 132

Answers (3)

Love Trivedi
Love Trivedi

Reputation: 4046

    #nav {
        height: 60px;
        border: 1px solid #ccc;  
display:table;  
    }

    #menu {
        width: 70px;
        height: 30px;
        margin-top: 15px;
        float: left;
        background: #ccc;
display: inline-table;
    }

    #logo {
        width: 200px;
        height: 30px;
        margin: 15px auto 0 auto;
        background: #ccc;
display: inline-table;
    }

    #settings {
        width: 70px;
        height: 30px;
        margin-top: 15px;
        float: right;
        background: #ccc;
        display:inline-table
    }

Upvotes: 0

Mr. Alien
Mr. Alien

Reputation: 157284

I'll explain you what's going on there, you have your first div set to float: left; which will float nicely, now your second div isn't floated either left or right so it's taking entire available horizontal space leading the third div to render below.

Demo

#logo {
    width: 200px;
    height: 30px;
    margin: 15px auto 0 auto;
    background: #ccc;
    float: left;
    margin-left: 120px;
}

Now am aware of the fact that you want to center align your #logo so in this case, make your #logo div position: absolute;

#nav {
    height: 60px;
    border: 1px solid #ccc;   
    position: relative; /* Be sure you use this else your div will fly out in the wild */
}

#logo {
    width: 200px;
    height: 30px;
    margin: 15px auto 0 auto;
    background: #ccc;
    position: absolute; /* Takes your element out of the flow*/
    left: 50%; /* 50% from the left */
    margin-left: -100px; /* 1/2 of total width to ensure that it's exactly centered */
}

Demo 2

Upvotes: 1

psd2htmldepot
psd2htmldepot

Reputation: 192

You must float also the #logo;

 #logo {
    float:left;
    width: 200px;
    height: 30px;
    margin: 15px auto 0 auto;
    background: #ccc;
}

example

Upvotes: 0

Related Questions