How to center an ul element

by krike in Tutorials on 12 Nov 2010


Sometimes I need to center an unordered list to the center of my page, mainly for navigations. But aligning an ul to the center can be somehow tricky. You can of course set the left and right margin to auto:

margin:0 auto;

But the problem is that you must add a fixed width to the ul element in order to center it. However when you create a premium template you never know how many list items the user will add, he might need to increase or decrease the width to center the navigation properly.

But wouldn’t it be easier to make sure the navigation is centered to the middle without having to change the width or not have the use a width at all? Of course it is!

So like any person I started googling and quickly found a solution:

#nav-menu
{
	text-align:center;
	overflow: hidden;
}

#nav-menu li
{
	
	font-size:small;
	float: left;
	left: -50%;
	position: relative;
	padding: 0;
	margin: 0;
}

 #nav-menu ul
{
	list-style: none;
	padding: 0;
	margin: 0;
	float: left;
	left: 50%;
	position: relative;
	text-align: center;
}

Written by krike

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam sit amet nisl nisl. Ut interdum libero vitae quam ultricies et lacinia elit aliquet. Praesent tincidunt, sem tempus feugiat feugiat, turpis tellus scelerisque erat, sit amet feugiat neque arcu ac lectus. Sed at mi et elit interdum scelerisque vitae eu felis.

krike has written 77 posts.

  • overlfow: hidden;
    should be
    overflow: hidden;

    • @chris little typo, thank you for letting me know

  • Sharath

    That was very helpful. Thanks mate!