如何水平居中对齐列表?

时间:2015-07-23 15:00:52

标签: html css

我有这个网站:LINK

HTML:

<ul id="portfolio">
    <li class="item item-cat photo1 photo mix_all" style="display: inline-block;  opacity: 1;"></li>
    <li class="item item-cat photo1 photo mix_all" style="display: inline-block;  opacity: 1;">// SOME CODE HTML</li>
    <li class="item item-cat photo1 photo mix_all" style="display: inline-block;  opacity: 1;">// SOME CODE HTML</li>
    <li class="item item-cat photo1 photo mix_all" style="display: inline-block;  opacity: 1;">// SOME CODE HTML</li>
    <li class="item item-cat photo1 photo mix_all" style="display: inline-block;  opacity: 1;">// SOME CODE HTML</li>
    <li class="item item-cat photo1 photo mix_all" style="display: inline-block;  opacity: 1;">// SOME CODE HTML</li>
    <li class="item item-cat photo1 photo mix_all" style="display: inline-block;  opacity: 1;">// SOME CODE HTML</li>     
</ul>

CSS:

@media screen and (max-width:770px) {
  .item-cat{width:100% !important;}
}

.item-cat {
  width:25%;
  max-width:360px;
  float:left;
  position:relative;
}

我画了一张照片,以了解我想做什么。

enter image description here

如何对齐此列表中心? 我尝试添加text-align: centermargin: 0 auto,但遗憾的是它不起作用。

请告诉我如何解决这个问题?

4 个答案:

答案 0 :(得分:1)

对于按块到中心,您不仅需要margin,还需要width。将此添加到您的CSS:

@media screen and (max-width:770px)
    #portfolio {
        margin: 0 auto;
        width: 360px;
    }
}

宽度是li元素中图像的宽度。

答案 1 :(得分:1)

您可以尝试使用flexbox。这是一个例子:

#container{
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: grey;
 flex-direction: row;
   flex-wrap: wrap;
}
#container > div{
    display:block;
    background-color:blue;
    width:60px;
    height:60px;
}
<div id="container">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>

https://jsfiddle.net/h9Ly1fc4/1/

您可以在此处检查Flexbox的浏览器兼容性: http://caniuse.com/#feat=flexbox

答案 2 :(得分:1)

删除float:left;并将父级或容器div设置为text-align:center;

img{
  width:200px;
}

body{
  text-align:center;
}
<a href="#">
  <img src="http://i.stack.imgur.com/scc80.png">
</a>

答案 3 :(得分:1)

您似乎需要调整媒体查询中的样式:

@media screen and (max-width:770px){
  .item-cat {
    width: 100%;
    float: none; /*remove the float*/
    display: block; /*set to display block, for centering*/
    margin: 0px auto; /*center using margin*/
  }
}