Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

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

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

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

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...