繁体   English   中英

在DIV中将UL水平居中

[英]Center a UL horizontally within a DIV

我目前正在尝试在<div>中将<ul>水平居中,并且不是为了让步,我尝试了margin: 0 auto; text-align: center; 而且似乎都不起作用。

演示版

的HTML

<!-- START RECENT WORK -->
<div id="recentwork">
  <div class="display">
    <h2>Recent Work</h2>
    <ul>
      <li class="recent"><img src="http://www.gezzamondo.co.uk/images/apps/ticketsoup/ticketsoup-01.jpg" /></li>
      <li class="recent"><img src="http://www.gezzamondo.co.uk/images/apps/ticketsoup/ticketsoup-01.jpg" /></li>
      <li class="recent last"><img src="http://www.gezzamondo.co.uk/images/apps/ticketsoup/ticketsoup-01.jpg" /></li>
    </ul>
  </div>

</div>
<!-- CLOSE RECENT WORK -->

的CSS

#recentwork {
    width: 100%;
    background-color: #ececec;
    clear: both;
    padding: 80px 0;
}

#recentwork .display {
    width: 960px;
    margin: 0 auto;
    overflow: hidden;
}

#recentwork .display ul {
    margin: 0 auto;
    padding: 0;
    list-style: none;
}

#recentwork .display ul li.recent {
    float: left;
    margin-right: 30px;
    width: 200px;
}

#recentwork .display ul li.recent.last {
    margin-right: 0!important;
}

让我们使用通过display: inline-block的老式技巧: 将列表居中 display: inline-block 这样做:

#recentwork .display {
    overflow: hidden;
    text-align: center;
}

#recentwork .display ul {
    display: inline-block;
    padding: 0;
    list-style: none;
}

#recentwork .display ul li.recent {
    display: inline-block;
    margin-right: 30px;
    width: 200px;
}

小提琴: http : //jsfiddle.net/praveenscience/pU2Gx/3/

margin: 0 auto只有在宽度固定的情况下, margin: 0 auto才会起作用。

我假设您希望各个列表项在列表本身内仍保持左对齐 在这种情况下,请尝试以下操作:

<div class="centerlist">
  <ul>
    <li>List item</li>
    <li>List item</li>
    <li>A longer list item than the other two</li>
  </ul>
</div>

而这个CSS:

.centerlist {
    text-align: center;
}
.centerlist > ul {
    display: inline-block;
    text-align: left;
}

尝试这个:

#recentwork {
    width:100%;
    background-color:#ececec;
    clear:both;
    padding:80px 0;
}

.display {
    width:960px;
    margin:0 auto;
    overflow:hidden;
}

.display ul {
    display: block;
    margin:0 auto;
    padding:0;
    list-style:none;
    text-align: center;
    width: 820px;
}

.recent{
    display: inline-block;
    padding: 0;
    margin: 0;
    width: 270px;
}

请注意display: inline-block的使用和适当宽度的使用。

http://jsfiddle.net/Z6LJE/

您的ul需要有一个宽度才能居中。

例如:

#recentwork .display ul {
    margin:0 auto;
    padding:0;
    list-style:none;
    width:700px;
}

jsFiddle示例

修改以下CSS:

#recentwork .display ul {
    display: block;
    list-style: none;
    margin: 0 auto;
    padding: 0;
    text-align: center;
}

#recentwork .display ul li.recent {
    display: inline-block;
    margin-right: 30px;
    width: 200px;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM