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

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

当前回答

使用 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!

其他回答

<div class="container">
<div class="res-banner">
<img class="imgmelk"  src="~/File/opt_img.jpg" >
</div>
</div>

CSS 代码

.res-banner{
        width:309px;
        margin: auto;
        height:309px;
    }

它不能集中,如果你不给它一个宽度,否则,它将采取,默认情况下,整个水平空间。

使用下面的代码。

HTML

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

CSS

#outer {
  text-align: center;
}
#inner{
  display: inline-block;
}

而不是多种包装和/或自动边缘,这个简单的解决方案对我来说工作:

<div style="top: 50%; left: 50%;
    height: 100px; width: 100px;
    margin-top: -50px; margin-left: -50px;
    background: url('lib/loading.gif') no-repeat center #fff;
    text-align: center;
    position: fixed; z-index: 9002;">Loading...</div>

它将Div放在视图(垂直和水平)的中心,尺寸和调整尺寸,中心背景图像(垂直和水平),中心文本(水平),并保持Div在视图和内容的顶部。

<div id="outer" style="width:100%;margin: 0 auto; text-align: center;"> <div id="inner">Foo foo</div> </div>