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
333 views
in Technique[技术] by (71.8m points)

html - How to center an unordered list?

I need to center an unordered list of unknown width, while still keeping the list-items left aligned.

Achieve the same result as this:

HTML

<div>
    <ul>
        <li></li>
        <li></li>
        <li></li>
    </ul>
</div>

CSS

div { text-align: center; }
ul { display: inline-block; text-align: left; }

Except my <ul> doesn't have a parent div. ul { margin: 0 auto; } doesn't work because I don't have a fixed width. ul { text-align: center; } doesn't work because the list-items won't be left aligned anymore. So how can I center this <ul> while keeping the <li>s left aligned (without having a parent div wrapper)?

<ul>
    <li></li>
    <li></li>
    <li></li>
</ul>

EDIT: Perhaps my wording wasn't the best... The first block of code already works... what i need is to do it without the <div> wrapper, if that's possible of course. Float tricks? Pseudo element tricks? There must be a way.

question from:https://stackoverflow.com/questions/19443013/how-to-center-an-unordered-list

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

1 Reply

0 votes
by (71.8m points)

ul {
  display: table;
  margin: 0 auto;
}
<html>

<body>
  <ul>
    <li>56456456</li>
    <li>4564564564564649999999999999999999999999999996</li>
    <li>45645</li>
  </ul>
</body>

</html>

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

...