I have this html structure
<div class="top_menu">
<ul>
<li class="left"><a href="" class="family-filter">asdas</a></li>
<li class="welcome">Welcome <span class="username">Guest</span></li>
<li class="right"><a href="#">Login</a></li>
</ul>
</div>
and this css code:
.top_menu {
padding: 20px; background-color: #fff;
-webkit-border-bottom-right-radius: 5px;
-webkit-border-bottom-left-radius: 5px;
-moz-border-radius-bottomright: 5px;
-moz-border-radius-bottomleft: 5px;
border-bottom-right-radius: 5px;
border-bottom-left-radius: 5px;
}
.top_menu ul { margin: 0; padding: 0; line-height: 0; }
.top_menu ul li { display: inline; margin: 0; padding: 0; border: 1px solid red; }
.top_menu ul .welcome { text-align:center; }
.top_menu ul li a { font-size: 14px; }
I am trying to align .welcome
to middle of .top_menu > ul
. I've tried the above and this:
.center {
margin-left: auto;
margin-right: auto;
display: block;
clear: both;
}
but no success, any ideas? http://jsfiddle.net/U2mfK/
You are defining .welcome
before you are defining the global styles for the li
. This will mean any styles in the .top_menu ul li
will override the styles in the .welcome (display:block;). Put it below like this:
.top_menu ul { margin: 0; padding: 0; line-height: 0; }
.top_menu ul li { display: inline; margin: 0; padding: 0; border: 1px solid red; }
.top_menu ul .welcome { text-align:center; display: block; margin: 0 auto; }
.top_menu ul li a { font-size: 14px; }
UPDATE
By positioning the outside li
tags absolutely, you are able to prevent them from pushing the center li
off center.
Like this (I have only included the additional styles for clarity):
.top_menu ul { position: relative; }
.top_menu ul .left { position: absolute; left: 0; }
.top_menu ul .welcome { text-align:center; display: block; margin: 0 auto; }
.top_menu ul .right { position: absolute; right: 0; }
Alternatively, you could leave the .left
and .right
as they are with their floats, and just position the center element absolutely like this:
.top_menu ul { position: relative; }
.top_menu ul .left { float: left; }
.top_menu ul .welcome { text-align:center; display: block; position: absolute; left: 50%; margin-left: -100px; width: 200px; }
.top_menu ul .right { float: right; }
If you use the above method, make sure margin-left
is half the width. You MUST specify a width for this method. If you just make it larger than content, it will center the content because of the text-align: center
so this should not be a problem