I have a #header
div that is 100% width
and within that div I have an unordered list. I have applied margin: 0 auto
to the unordered list but it won't center it within the header div.
Can anybody please tell me why? I thought that if I define the width of the parent div, then the unordered list should be able to center itself with margin: 0 auto
. What am I missing?
Here is my code:
<style>
* {
margin: 0;
padding: 0;
}
#header {
width: 100%;
background-color: #333;
min-height: 160px;
font-family:Arial, Helvetica, sans-serif;
}
#sitename {
font-size: 50px;
width: 620px;
margin:0 auto;
padding-top: 35px;
color:#999;
}
#header ul {
float: right;
margin: 0 auto;
}
#header ul li {
float: left;
padding-right: 20px;
list-style-type: none;
font-size: 20px;
}
</style>
</head>
<body>
<div id="header">
<h1 id="sitename">Photography Auction Site</h1>
<ul>
<li>List of Photos</li>
<li>Image Gallery</li>
<li>Contact Us</li>
</ul>
</div>
</body>
</html>
We can set the width for ul tag then it will align center.
Why not?
I don't know why the first answer is the best one, I tried it and not working in fact, as @kalys.osmonov said, you can give
text-align:center
toheader
, but you have to makeul
asinline-block
rather thaninline
, and also you have to notice thattext-align
can be inherited which is not good to some degree, so the better way (not working below IE 9) is usingmargin
andtransform
. Just removefloat right
andmargin;0 auto
fromul
, like below:This way can fix the problem that making dynamic width of
ul
center if you don't care IE8 etc.You need to define the width of the element you are centering, not the parent element.
Edit: Ok, I've seen the testpage now, and here is how I think you want it:
An inline-block covers the whole line (from left to right), so a margin left and/or right won't work here. What you need is a block, a block has borders on the left and the right so can be influenced by margins.
This is how it works for me: