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

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

当前回答

此分類上一篇: Margin:0px auto:

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

其他回答

要在中间调整一个 div 中间的 div -

.outer{ 宽度: 300px; /* 例如 */ 高度: 300px; /* 例如 */ 背景: 红色; }.inner{ 位置: 相对; 顶部: 50%; 左: 50%; 转换: 翻译(-50%, -50%); 宽度: 200px; 高度: 200px; 背景: 黄色; } <body> <div class='outer'> <div class='inner'></div> </div> </body>

这将使中间的内部迪夫均匀,垂直和水平。

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

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

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

我们可以使用下一个CSS的类,允许中心垂直和垂直对其父母的任何元素:

.centerElement{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

最简单的方式之一......

<!DOCTYPE html>
<html>
    <head>
        <style>
            #outer-div {
                width: 100%;
                text-align: center;
                background-color: #000
            }
            #inner-div {
                display: inline-block;
                margin: 0 auto;
                padding: 3px;
                background-color: #888
            }
        </style>
    </head>

    <body>
       <div id ="outer-div" width="100%">
           <div id ="inner-div"> I am a easy horizontally centered div.</div>
       <div>
    </body>
</html>
div{
    width: 100px;
    height: 100px;
    margin: 0 auto;
}

通常情况下,如果您正在使用DIV静态方式。

如果你想要一个Div集中在Div是绝对的父母,这里是例子:

.parentdiv{
    position: relative;
    height: 500px;
}

.child_div{
   position: absolute;
   height: 200px;
   width: 500px;
   left: 0;
   right: 0;
   margin: 0 auto;
}