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

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

当前回答

这就是你想要的最短的方式。

JSFIDDLE

#outer {
  margin - top: 100 px;
  height: 500 px; /* you can set whatever you want */
  border: 1 px solid# ccc;
}

#inner {
  border: 1 px solid# f00;
  position: relative;
  top: 50 % ;
  transform: translateY(-50 % );
}

其他回答

我创建了这个例子,以表明如何垂直和水平地调整。

这个代码基本上就是这样:

#outer {
 position: relative;
}

和...

#inner {
  margin: auto;
  position: absolute;
  left:0;
  right: 0;
  top: 0;
  bottom: 0;
}

它会留在中心,即使你重新启动屏幕。

如果您不想设置固定宽,并且不需要额外的边界,则将显示器添加到您的元素中: inline-block。

你可以使用:

#element {
    display: table;
    margin: 0 auto;
}

试试这:

<div id="a">
    <div id="b"></div>
</div>

CSS:

#a{
   border: 1px solid red;
   height: 120px;
   width: 400px
}

#b{
   border: 1px solid blue;
   height: 90px;
   width: 300px;
   position: relative;
   margin-left: auto;
   margin-right: auto;
}

.outer - 完整的宽度.inner - 没有宽度设置(但可以指定最大宽度)

假设计算的元素的宽度为1000像素和300像素。

在.center-helper 中插入.center-helper 创建.center-helper 一个内线区块; 它变成相同的尺寸.center 使其宽 300 像素. 按.center-helper 50% 相对其父母; 此位置其左在 500 像素. 向外. 按.center-helper 50% 相对其父母; 此位置其左在 -150 像素. 向中帮助, 这意味着其左在 500 - 150 = 350 像素。

演示:

这就是你想要的最短的方式。

JSFIDDLE

#outer {
  margin - top: 100 px;
  height: 500 px; /* you can set whatever you want */
  border: 1 px solid# ccc;
}

#inner {
  border: 1 px solid# f00;
  position: relative;
  top: 50 % ;
  transform: translateY(-50 % );
}