Close up of computer code on a screen

Centring your unordered list with an unknown width

Rick Baxter avatar
by Rick Baxter
Creative Director
Posted 11 Jan 2019

Ever struggled to position your unordered list in the centre with HTML and CSS. Struggle no more…

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 because 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.

Recent articles

Illustrated web design North East England map

Top 5 Website Projects for North East Clients

Transforming web design in Newcastle, Hartlepool and East Durham with these standout projects for educational and community organisations.

14 Jan 2025
Accessible Web Design - East Durham College

Accessible Web Design for Local Education

Learn about essential tips, legal obligations, common barriers, and tools for creating inclusive educational websites.

02 Jan 2025
J Allcocks & Sons website on iMac

Creating a web presence for J. Allcock & Sons LTD

Discover how Fat Heads designed a sleek, eco-friendly website for a 100-year-old leader in rubber recycling and sustainability.

19 Dec 2024
Drupal 7 - End of Life

Drupal 7: A Critical Warning

Discover why Drupal 7 sites are a ticking time bomb for UK businesses. Learn about critical security risks, potential breaches, and how to protect your digital assets now.

29 Nov 2024