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

<div id="outer">
  <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 的老式同步的老式浏览器,这里是一个很好的地方去看。

其他回答

中心一个Div在一个Div

.outer { 显示: -webkit-flex; 显示: flex; //-webkit-justify-content: center; //justify-content: center; //align-items: center; width: 100%; height: 100px; background-color: lightgrey; }.inner { 背景颜色: cornflowerblue; padding: 2rem; margin: auto; //align-self: center; } <div class="outer"> <div class="inner"

CSS 定义内容属性

它将Flexbox元件调整到容器的中心:

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

只需将此 CSS 内容添加到您的 CSS 文件中,它将自动集中内容。

垂直调整到CSS中中心:

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

垂直 + 垂直到中心在 CSS 中:

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

与网

一个非常简单和现代的方式是使用显示器:网:

div { 边界: 1px dotted 灰色; } #outer { 显示: 网; 地点标题: 中心; 高度: 50px; /* 不需要 */ } <!DOCTYPE html> <html> <head> </head> <body> <div id="outer"> <div> Foo foo</div> </div> </body> </html>

有几种方法可以实现这一点:使用“flex”,“positioning”,“margin”等。

我推荐使用“Flex”

#outer {
   display: flex;
   justify-content: center;
   align-items: center;  /* if you also need vertical center */
}

使用地平线定位

#outer {
  position: relative;
}
#inner {
  position: absolute;
  left: 50%;
  translate: transformX(-50%)
}

垂直和垂直,使用定位

#outer {
  position: relative;
}
#inner {
  position: absolute;
  left: 50%;
  top: 50%;
  translate: transform(-50%, -50%)
}

使用边界的垂直调整

#inner {
 width: fit-content;
 margin: 0 auto;
}