Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I center a <ul> with left-aligned <li>s?

Tags:

html

css

I'd like to center a list of left-aligned items.

This is what I currently have:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Shrinkwrapped List</title>
    <style type="text/css">
      #wrapper {
        margin: auto;
        width: 500px;
        border: solid 1px #CCCCCC;
      }
      #header {
        text-align: center;
       font-size: 200%;
      }
      #content {
        text-align: center;
      }
      #content ul {
        text-align: left;
        font-size: 150%;
        list-style-type: none;
        margin: 20px auto;
        padding: 0px;
        border: solid 1px #666666;
      }
    </style>
  </head>
  <body>
    <div id="wrapper">
      <div id="header">
        Shrinkwrapped List
      </div>
      <div id="content">
        <ul>
          <li>Lorem ipsum</li>
          <li>Dolor sit amet</li>
          <li>Consectetur</li>
          <li>Adipiscing elit</li>
          <li>Morbi odio</li>
          <li>Mi blandit vehicula</li>
        </ul>
      </div>
    </div>
  </body>
</html>

Which produces a page that looks like:

Not really what I want

What I really want looks like this:

This is the look I want

I can accomplish this by adding width: 200px; to #content ul but the problem is that I have a lot of lists like this and they all have various widths.

I'd like the <ul> to shrink to the content so it can be centered correctly. Or am I going about this the wrong way?

Thanks for any help you can provide.


Solution

Thanks to KennyTM and Magnar, here is the solution:

Add these four lines to #content ul's CSS rules:

display:-moz-inline-stack;
display:inline-block;
zoom:1;
*display:inline;

I've tested this in IE6, IE7, IE8 and Firefox 3.6. The results looks like the second image above and the list always fits to the content of the items.

like image 779
Travis Avatar asked Sep 01 '25 21:09

Travis


2 Answers

Set the <ul> to use display: inline-block;. See http://jsbin.com/atizi4.

Note that inline-block is not supported (completely) for IE ≤7.

like image 158
kennytm Avatar answered Sep 04 '25 07:09

kennytm


You can probably adopt my previous answer. Inline-block for IE, display:table for modern browsers. Might need to explicitly specify a list-style-type.

Edit: Since this is a list, may be able to get away with inline-block on the ul and not display:table. You need to declare in a separate rule, display:inline; after inline-block for IE.

like image 22
meder omuraliev Avatar answered Sep 04 '25 07:09

meder omuraliev