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

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

当前回答

好吧,我找到了一个可能适合所有情况的解决方案,但使用JavaScript:

这里是结构:

<div class="container">
  <div class="content">Your content goes here!</div>
  <div class="content">Your content goes here!</div>
  <div class="content">Your content goes here!</div>
</div>

此分類上一篇: JavaScript snippet:

$(document).ready(function() {
  $('.container .content').each( function() {
    container = $(this).closest('.container');
    content = $(this);

    containerHeight = container.height();
    contentHeight = content.height();

    margin = (containerHeight - contentHeight) / 2;
    content.css('margin-top', margin);
  })
});

如果你想用它在一个响应性方法,你可以添加以下:

$(window).resize(function() {
  $('.container .content').each( function() {
    container = $(this).closest('.container');
    content = $(this);

    containerHeight = container.height();
    contentHeight = content.height();

    margin = (containerHeight - contentHeight) / 2;
    content.css('margin-top', margin);
  })
});

其他回答

一个非常简单的和跨浏览器的答案到水平中心是将这个规则应用到母元素:

.parentBox {
    display: flex;
    justify-content: center
}

最好的方法是使用桌面细胞显示器(内部),即与显示表(外部)的Div之后,并为内部Div(与桌面细胞显示器)设置垂直调整,并在Div或页面中心的内部Div中使用的每个标签。

注意:您必须将指定的高度设置到外面

它是最好的方式你知道没有位置相对或绝对,你可以使用它在每个浏览器一样。

#outer{ 显示: 表; 高度: 100vh; 宽度: 100%; } #inner{ 显示: 表细胞; 垂直平衡: 中间; 文本平衡: 中心; } <div id="outer"> <div id="inner"> <h1> 设置内容中心 </h1> <div> hi 这是最适合您的项目中心 </div> </div> </div> </div>

<html>

*{ margin: 0; padding: 0; } #outer{ 背景: 红色; 宽度: 100%; 高度: 100vh; 显示: flex; /*center 垂直*/ 正当内容: 中心; flex 方向: 列; /*center 垂直*/ 匹配元素: 中心; } #inner{ 宽度: 80%; 高度: 40px; 背景: g

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

我最近找到了一个方法:

#outer {
    position: absolute;
    left: 50%;
}

#inner {
    position: relative;
    left: -50%;
}

两个元素必须是相同的宽度,以便正常运作。