html - 如何使 float 列表居中?

标签 html css flexbox

这是我的页面的样子:

enter image description here

现在当我添加另一个帖子时:

enter image description here

它向左对齐,但我希望它们居中。

如何让它们居中?

#demo {
    float: left;
    margin: 0 auto;
    width: 980px;
    list-style: none;
}
#demo li {
    background: #fec722;
    float: left;
    margin: 10px 0 10px 15px;
    width: 178px;
}
#demo img {
    height: 243px;
    margin: 3px;
    width: 172px;
}
<ul id="demo">
    <li><img src="http://goo.gl/0nSAIH"></li>
    <li><img src="http://goo.gl/0nSAIH"></li>
</ul>

( JSFiddle )

最佳答案

您真正需要的只是两行代码(您可以摆脱所有的 float 和 clearfix div):

#shelf {
    display: flex;
    justify-content: center;
}

Revised Fiddle


flexbox 的优势:

  1. 最少的代码;非常有效率
  2. > centering, both vertically and horizontally, is simple and easy
  3. > equal height columns are simple and easy
  4. > multiple options for aligning flex elements
  5. react 灵敏
  6. 与 float 和表格不同,它们提供有限的布局能力,因为它们从未用于建筑布局,而 flexbox 是一种具有广泛选项的现代 (CSS3) 技术。

要了解有关 flexbox 的更多信息,请访问:


请注意所有主流浏览器都支持 flexbox,except IE 8 & 9 .一些最新的浏览器版本,例如 Safari 8 和 IE10,需要 vendor prefixes .要快速添加所需的所有前缀,请在此处的左侧面板中发布您的 CSS:Autoprefixer .更多详细信息,请参阅 this answer .

关于html - 如何使 float 列表居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35283108/

相关文章:

html - CSS 悬停 + div 不起作用

html - 两个 div 并排并清除第三个 div 的 flex

html - Flexbox 证明内容不适用于 flex-flow 列

html - 为什么显示:block not stretch buttons or input elements

HTML 使用 Bootstrap CSS 没有响应

css - Google 字体中的数字显示不同

html - 如何在div内绝对定位Bootstrap导航栏而不换行

html - 如何让两个div一样高

javascript - 将 ng-model 绑定(bind)到 get 和 set 的异步函数

php - 我如何使用 cookie 来存储购物车内容?