Think-Outside-The-Box

The Problem:
I want to display a list horizontally, but I want the entire list to be centered on my page.

Skip to the code

Intro/Background/SEO Filler

I have recently figured out a long time frustration of mine, so I figured I would jump on here and share it with the world. You’re welcome.  

For years I have had a reoccurring annoyance, where I am given a list that must be centered on a page yet all individual items appear next to each other. In HTML speak, I want to place an “Unordered List” <ul>  or an “Ordered List” <ol> on my page centered, but, I want the “List Items” <li> to be floating next to each other. I have “solved” this problem in the past by floating all the <li> left using CSS (float: left;). Then I set a width on the <ul> or <ol> and give it an auto-assigned margin using CSS (width: 500px; margin: 0 auto;). This has been fine I guess. It just makes it a pain to perform mobile responsive CSS on the list. Because as the text shrinks you have to assign a new width to the <ul> or <ol> at multiple sizes. 

The Solution:

For some reason today as I was faced with this same problem it dawned on me that maybe I was thinking about this all wrong. Instead of trying to manipulate these list items to do my bidding within their blocks, I needed to remove the block styling and treat them as paragraph text. So simple. 

All that needs to be done is to set your <ul> or <ol> as position: relative; so it holds down the fort, display: block; so it takes up the space, and then give it a text-align: center;

Next, tell your <li> to have a width: auto; and to, and this is the magic, display: inline; Works every time, palm to forehead.

Sometimes, thinking outside the box is all it takes in CSS. #reallyproudofthatpun

 

Example:

  • List Item 1
  • List Item 2
  • List Item 3

 

The Code:

ul,
ol {
    position: relative;
    display: block;
    text-align: center;
}
li {
    width: auto;
    display: inline;
}