Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
553 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...