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

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

当前回答

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

其他回答

是的,这是一个短暂而干净的水平调整代码。

.classname {
   display: box;
   margin: 0 auto;
   width: 500px /* Width set as per your requirement. */;
}

您可以使用显示器: flex 为您的外部 div 和到水平中心 您必须添加 justify 内容: 中心

#outer{
    display: flex;
    justify-content: center;
}

或者您可以参观w3schools - CSS flex Property 更多想法。

设置宽度,并设置边缘向左和边缘向右到自动。 这是仅限于水平,但是. 如果你想要两种方式,你只会做这两种方式. 不要害怕尝试; 它不像你会打破任何东西。

我创建了这个例子,以表明如何垂直和水平地调整。

这个代码基本上就是这样:

#outer {
 position: relative;
}

和...

#inner {
  margin: auto;
  position: absolute;
  left:0;
  right: 0;
  top: 0;
  bottom: 0;
}

它会留在中心,即使你重新启动屏幕。

如果有人想要一个 jQuery 解决方案的中心调整这些 divs:

$(window).bind("load", function() {
    var wwidth = $("#outer").width();
    var width = $('#inner').width();
    $('#inner').attr("style", "padding-left: " + wwidth / 2 + "px; margin-left: -" + width / 2 + "px;");
});