对齐float:left div居中?


97

我想让一组图像在页面上水平显示。每个图像下方都有一些链接,因此我需要在每个图像/链接组周围放置一个容器。

我最想要的就是将它们放在float:left的div中。问题是我希望容器对齐中心而不是左对齐。我该如何做到这一点。

Answers:


218

使用display:inline-block;而不是浮动

您不能将浮动框居中,而将内嵌块居中放置,就好像它们是文本一样,因此在“行”的外部整体容器上-您可以text-align: center;为每个图像/标题容器设置(可以是inline-block;) -如果需要,请向左对齐文本


3
以防万一有人在元素之间出现空格,请通过定义元素来删除代码中的空白,例如'<img> </ img> <img> </ img>'或'<img> < / img> <!-评论-> <img> </ img>'。
Maarten 2013年

1
或设置父元素font-size:0并将其还原到子元素上。或letter-spacing:-.31em在父母和letter-spacing:0孩子身上使用。
Mike Causer 2014年

@Baumr改用flexbox。下面有一个例子
Jan Derk

3
您可能需要添加vertical-align:middle同时使用display:inline-block
2015年

47

如今, CSS Flexbox得到了很好的支持转到此处,获得有关flexbox的良好教程。

在所有较新的浏览器中都可以正常工作:

#container {
  display:         flex;
  flex-wrap:       wrap;
  justify-content: center;
}

.block {
  width:              150px;
  height:             150px;
  background-color:   #cccccc;
  margin:             10px;        
}
<div id="container">
  <div class="block">1</div>    
  <div class="block">2</div>    
  <div class="block">3</div>    
  <div class="block">4</div>    
  <div class="block">5</div>        
</div>

有人可能会问为什么不使用display:inline-block?对于简单的事情,这很好,但是如果您在块中包含复杂的代码,则布局可能不再正确居中。Flexbox比向左浮动更稳定。


这适用于水平居中。垂直居中如何?
Cullub

要垂直居中,请给容器一个高度(例如,高度:500px;)并添加align-items:center;
Jan Derk

9

尝试这样:

  <div id="divContainer">
    <div class="divImageHolder">
    IMG HERE
    </div>
    <div class="divImageHolder">
    IMG HERE
    </div>
    <div class="divImageHolder">
    IMG HERE
    </div>
    <br class="clear" />
    </div>

    <style type="text/css">
    #divContainer { margin: 0 auto; width: 800px; }
    .divImageHolder { float:left; }
    .clear { clear:both; }
    </style>

9

只需将浮动元素包装在中,<div>然后提供以下CSS:

.wrapper {

display: table;
margin: auto;

}

1

也许这就是您正在寻找的-https://www.w3schools.com/css/css3_flexbox.asp

CSS:

#container {
  display:                 flex;
  flex-wrap:               wrap;
  justify-content:         center;
}

.block {
  width:              150px;
  height:             150px;
  margin:             10px;        
}

HTML:

<div id="container">
  <div class="block">1</div>    
  <div class="block">2</div>    
  <div class="block">3</div>          
</div>

0
.contentWrapper {
    float: left;
    clear: both;
    margin-left: 10%;
    margin-right: 10%;
}

.repeater {
    height: 9em;
    width: 9em;
    float: left;
    margin: 0.2em;
    position: relative;
    text-align: center;
    cursor: pointer;
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.