我如何用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);
  })
});

其他回答

使用 Sass (SCSS合成) 你可以用混合物做到这一点:

与翻译

// Center horizontal mixin
@mixin center-horizontally {
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
}

// Center horizontal class
.center-horizontally {
    @include center-horizontally;
}

在HTML标签中:

<div class="center-horizontally">
    I'm centered!
</div>

请记住添加位置:相对;到母 HTML 元素。


与Flexbox

使用Flex,你可以这样做:

@mixin center-horizontally {
  display: flex;
  justify-content: center;
}

// Center horizontal class
.center-horizontally {
    @include center-horizontally;
}

在HTML标签中:

<div class="center-horizontally">
    <div>I'm centered!</div>
</div>

试试这个CodePen!

这将你的内心分散为垂直和垂直:

#outer{
    display: flex;
}
#inner{
    margin: auto;
}

只有垂直调整,变化

margin: 0 auto;

垂直,变化。

margin: auto 0;

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

如果您不想设置固定宽,并且不需要额外的边界,则将显示器添加到您的元素中: inline-block。

你可以使用:

#element {
    display: table;
    margin: 0 auto;
}

我知道我稍晚回答这个问题,我没有打扰阅读每一个答案,所以这可能是一个重复。

inner { width: 50%; background-color: Khaki; margin: 0 auto; }