我如何用CSS垂直集中一个 <div> 在另一个 <div> 中?

<div id="outer">
  <div id="inner">Foo foo</div>
</div>

当前回答

克里斯·科伊尔(Chris Coyier)在他的博客上写了一篇关于“在未知中集中”的好文章,这是一个多种解决方案的环节,我发表了一个没有发表在这个问题上,它有更多的浏览器支持,而不是Flexbox解决方案,你不使用显示:表;这可能会破坏其他事情。

/* This parent can be any width and height */
.outer {
  text-align: center;
}

/* The ghost, nudged to maintain perfect centering */
.outer:before {
  content: '.';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  width: 0;
  overflow: hidden;
}

/* The element to be centered, can
   also be of any width and height */
.inner {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}

其他回答

此分類上一篇: <div id="outer" style="width:100%"> <div id="inner">Foo foo</div> </div>

一些海报已经提到CSS 3的中心方式使用显示:盒子。

这个合成是过时的,不应该再使用。

因此,仅仅是为了完整性,这里是使用灵活盒子布局模块在CSS 3中集中最新的方式。

所以,如果你有简单的标签如:

<div class="box">
  <div class="item1">A</div>
  <div class="item2">B</div>
  <div class="item3">C</div>
</div>

...你想把你的物品集中在盒子内,这里是你需要的父母元素(.box):

.box {
    display: flex;
    flex-wrap: wrap; /* Optional. only if you want the items to wrap */
    justify-content: center; /* For horizontal alignment */
    align-items: center; /* For vertical alignment */
}

.box { 显示: flex; flex-wrap: wrap; /* 可选. 只有如果您想要的物品将 wrap */ 定义内容: 中心; /* 为水平调整 */ 定义项目: 中心; /* 为垂直调整 */ } * { 边界: 0; 粘贴: 0; } html, 身体 { 高度: 100%; }.box { 高度: 200px; 显示: flex; flex-wrap: 定义内容: 中心; 定义项目: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容

如果您需要支持使用 flexbox 的老式同步的老式浏览器,这里是一个很好的地方去看。

是的,这是一个短暂而干净的水平调整代码。

.classname {
   display: box;
   margin: 0 auto;
   width: 500px /* Width set as per your requirement. */;
}

Flex 有超过97%的浏览器支持覆盖范围,可能是解决这些问题的最佳方式:

#outer {
  display: flex;
  justify-content: center;
}

这将你的内心分散为垂直和垂直:

#outer{
    display: flex;
}
#inner{
    margin: auto;
}

只有垂直调整,变化

margin: 0 auto;

垂直,变化。

margin: auto 0;