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

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

当前回答

最簡單的方式之一是使用顯示器: flex. 外部 div 只需要顯示器 flex, 內部需要範圍: 0 auto 以使其以水平為中心。

要垂直集中,只需在另一个Div中集中一个Div,请查看下面的.inter 类评论。

.wrapper { 显示: flex; /* 添加我们想要的任何高度和宽度 */ 高度: 300px; 宽度: 300px; /* 只是这样你可以看到它是中心 */ 背景: peachpuff; }.inner { /* 中心 水平 */ 边界: 0 自动; /* 中心 垂直 * /* 边界: 0 自动; * /* 中心 * / * 边界: 0 自动; * / } <div class="wrapper"> <div class="inner"> 我是 ho

其他回答

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

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

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

演示:

有几种方法可以实现这一点:使用“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;
}

最简单的答案: 添加边界:自动; 到内部。

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

CSS 代码

.outer{
    width: 100%;
    height: 300px;
    background: yellow;
}

.inner{
    width: 30%;
    height: 200px;
    margin: auto;
    background: red;
    text-align: center
}

查看我的 CodePen 链接: http://codepen.io/feizel/pen/QdJJrK

此分類上一篇

#outer {postion: relative}
#inner {
    width: 100px; 
    height: 40px; 
    position: absolute;
    top: 50%;
    margin-top: -20px; /* Half of your height */
}

试试这:

<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;
}