CSS浮动图像在中心

时间:2014-12-20 08:08:21

标签: html css

所以我有图片+标题的HTML代码:

<div class="container">
<div class="box"><a href="#" class="catname"><img src="image1.jpg" class="thumb"><p>Title 1</p></a></div>
<div class="box"><a href="#" class="catname"><img src="image2.jpg" class="thumb"><p>Title 2</p></a></div>
<div class="box"><a href="#" class="catname"><img src="image3.jpg" class="thumb"><p>Title 3</p></a></div>
<div class="box"><a href="#" class="catname"><img src="image4.jpg" class="thumb"><p>Title 4</p></a></div>
...
<div class="box"><a href="#" class="catname"><img src="image49.jpg" class="thumb"><p>Title</p></a></div>
<div class="box"><a href="#" class="catname"><img src="image50.jpg" class="thumb"><p>Title</p></a></div>
</div>

和css:

.container {
    width:80%;
    margin: 0 auto;
}

.box {
    display:inline-block;
    width:150px;
    margin-right:5px;
    float:left;
}

使用该代码我在右边有更多的“白色”空间,我想在不设置容器宽度的情况下将这些图片放在中心以获得不同的浏览器大小。

是否可以使用css?

2 个答案:

答案 0 :(得分:1)

添加到容器类text-align:center;并删除float:left;从盒子类。

答案 1 :(得分:0)

这就是你所谓的中心无宽度浮动。

&#13;
&#13;
#outer {
  /* This is just so you can see that they're centered */
  width: 400px;
  border: 1px solid black;
  overflow: hidden;
}
.centered {
  position: relative;
  float: left;
  left: 50%;
  /* This and below is just because I have them stacked */
  height: 100px;
  padding-bottom: 10px;
  clear: left;
}
.centered div {
  position: relative;
  float: left;
  left: -50%;
}
&#13;
<div id="outer">
  <div class="centered">
    <div>
      <img src="http://placehold.it/200x100" alt="" />
    </div>
  </div>

  <div class="centered">
    <div>
      <img src="http://placehold.it/300x100" alt="" />
    </div>
  </div>

  <div class="centered">
    <div>
      <img src="http://placehold.it/50x100" alt="" />
      <img src="http://placehold.it/50x100" alt="" />
      <img src="http://placehold.it/50x100" alt="" />
      <img src="http://placehold.it/50x100" alt="" />
      <img src="http://placehold.it/50x100" alt="" />
    </div>
  </div>
</div>
&#13;
&#13;
&#13;