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

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

当前回答

如果你不想在内部DIV上设置固定宽度,你可以做这样的事情:

#outer { 宽度: 100%; 文本顺序:中心; } #inner { 显示: inline-block; } <div id="outer"> <div id="inner"> Foo foo</div> </div>

这使得内部的DIV变成一个可以与文本平行集中的内线元素。

其他回答

只是这样做:

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

CSS

#outer{
  display: grid;
  place-items: center;
}

克里斯·科伊尔(Chris Coyier)在他的博客上写了一篇关于“在未知中集中”的好文章,这是一个多种解决方案的环节,我发表了一个没有发表在这个问题上,它有更多的浏览器支持,而不是Flexbox解决方案,你不使用显示:表;这可能会破坏其他事情。

/* This parent can be any width and height */
.outer {
  text-align: center;
}

/* The ghost, nudged to maintain perfect centering */
.outer:before {
  content: '.';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  width: 0;
  overflow: hidden;
}

/* The element to be centered, can
   also be of any width and height */
.inner {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}

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

<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 {
    position: absolute;
    left: 50%;
}

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

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

好吧,我找到了一个可能适合所有情况的解决方案,但使用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);
  })
});