使用display: table-cell时,div元素无法居中

3
我最近一直在使用display: table以及display: table-cell来让我的html页面中的所有内容都居中显示。虽然对于段落、标题、输入框和标签等元素这样做是有效的(至少我测试过是有效的),但是似乎对于div元素无效。
是否有任何方法可以使这对div元素像其他元素一样有效?最好采用纯CSS解决方案。

示例也可在Codepen上查看

html {
  display: table;
  height: 100%;
  width: 100%;
  text-align: center;
}
body {
  display: table-cell;
  vertical-align: middle;
}
.hidden {
  display: none;
}
.leaf {
  border-radius: 15px 2px 15px 2px;
  border: 1px solid green;
  background-color: green;
  width: 250px;
  height: 80px;
}
<div class="leaf">Why am I not centered?</div>
<p>And why am I centered?</p>

2个回答

5

只需添加margin: 0 auto;即可。完美执行。

html {
  display: table;
  height: 100%;
  width: 100%;
  text-align: center;
}
body {
  display: table-cell;
  vertical-align: middle;
}
.hidden {
  display: none;
}
.leaf {
  border-radius: 15px 2px 15px 2px;
  border: 1px solid green;
  background-color: green;
  width: 250px;
  height: 80px;
  margin:0 auto;

}
<div class="leaf">Why am I not centered?</div>
<p>And why am I centered?</p>


它确实这样做,但为什么会这样呢?margin: 0 auto规则是如何让它做到的? - Angelos Chalaris
2
当您在应用了margin: 0 auto的对象上指定宽度时,该对象将居中于其父容器内。将第二个参数指定为auto基本上告诉浏览器自动确定左右边距,它通过设置相等的边距来实现。它保证左右边距将被设置为相同的大小。第一个参数0表示顶部和底部边距都将被设置为0。 - Prasath V

1
只需在 .leaf 类中添加 margin: 0 auto;。保留 HTML。

html {
  display: table;
  height: 100%;
  width: 100%;
  text-align: center;
}
body {
  display: table-cell;
  vertical-align: middle;
}
.hidden {
  display: none;
}
.leaf {
  margin: 0 auto;
  border-radius: 15px 2px 15px 2px;
  border: 1px solid green;
  background-color: green;
  width: 250px;
  height: 80px;
}
<div class="leaf">Why am I not centered?</div>
<p>And why am I centered?</p>


1
@Angelos,关于自动技巧的更多信息,请查看这里 - Divsign

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接