Centring your <ul> list with an unknown width

NEWS / Posted on the 11 January 2019

So you need to build that footer menu on your website and have it neatly centre aligned. Work out the width of the menu in pixels, add that to your <ul> tag in your CSS files and set the margin-left and margin-right to auto. Easy right? But what happens if you can't determine the width of the menu becuase the menu items can be renamed, added or removed by the client? This code will centre your unordered list regardless of the width.

The HTML:

<div class="container">
<div class="ul-container">
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</div>
<div class="clearfix"></div>
</div>

CSS

.ul-container {
float:right;
position: relative;
left: -50%;
}

ul {
position: relative;
left: 50%;
list-style: none;
}

.clearfix {
clear: both;
}

Essentially, the float: right in the container pushes the ul-container <div> contents to the right hand side of the container <div>. The left: -50% adjusts the ul-container <div>  back across so the right-hand edge of the ul-container <div> is exactly at the 50% mark of the container <div>. The left: 50% positions the left-hand edge of the <ul> at the 50% mark of the ul-container <div>. Both position: relative attributes link the ul-container <div> and the <ul> to each other and the clear:both kills the float:right attribute.

Bang! Right in the centre. Try it yourself.

Website development for South Manchester's Brookburn Primary School
Digital solution for Manchester Primary School
Fat Heads bring digital platforms together in Brookburn's new website
19 October 2018
Normhurst
Normhurst
Fat Heads working with Yorkshire-based Normhurst Limited to provide marketing support across its four major businesses
02 December 2007