使 div 在同一行居中

centering divs on the same line

我试图将这 3 个浮动 div 置于同一行的中心。这是 jsfiddle 的 link:

https://jsfiddle.net/dtps4fw8/2/

有什么建议吗?

HTML:

<div class="content">

    <div class="box">

    </div>
    <div class="box">

    </div>
    <div class="box">

    </div>

</div>

CSS:

.box {
width: 30%;
height: 200px;
float: left;
background: gray;
border: black solid 2px;
box-sizing: border;
margin: 5px;
}

看到这个fiddle

要使 3 div 居中,首先,删除 float属性,然后应用浮动效果,使用 display:inline-blockinline-block 显示给div 一个文本特征。父 div 的 text-align:center 会将这些 inline-block 元素置于父元素的中心。

更新您的 CSS 如下

.box {
  width: 30%;
  height: 200px;
  display: inline-block;
  background: gray;
  border: black solid 2px;
  box-sizing: border;
  margin: 5px;
}

.content {
  text-align: center;
}

首先,float:left; 与你的情况无关,就像 Lal 所说的,而不是 float:left; 它应该是 display:inline-block; 你也可以添加一个相对定位 position:relative;

我使用弹性盒子。非常简约且响应迅速。

.content {
  width:100%;
  display: flex;
  flex-direction:row;
  flex-wrap:wrap;}

.box {
  height: 200px;
  flex:1;
  background: gray;
  border: black solid 2px;
  box-sizing: border;
  margin: 5px;}