How do I center list items inside a ul without using extra divs or elements. I have the following. I thought text-align:center
would do the trick. I can't seem to figure it out.
<style>
ul {
width:100%;
background:red;
height:20px;
text-align:center;
}
li {
display:block;
float:left;
background:blue;
color:white;
margin-right:10px;
}
</style>
<ul>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
</ul>
Check jsfiddle http://jsfiddle.net/3Ezx2/1/
write display:inline-block
instead of float:left
.
li {
display:inline-block;
*display:inline; /*IE7*/
*zoom:1; /*IE7*/
background:blue;
color:white;
margin-right:10px;
}
A more modern way is to use flexbox:
ul{
list-style-type:none;
display:flex;
justify-content: center;
}
ul li{
display: list-item;
background: black;
padding: 5px 10px;
color:white;
margin: 0 3px;
}
div{
background: wheat;
}
<div>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</div>
li{
display:table;
margin:0px auto 0px auto;
}
This should work.
Looks like all you need is text-align: center;
in ul
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With