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

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

当前回答

我最近发现的一件好事,混合了线高度+垂直平行和50%左线技巧的使用,你可以在另一个动态尺寸的盒子内集中一个动态尺寸的盒子,在水平和垂直,使用纯粹的CSS。

请注意,您必须使用在现代浏览器 + Internet Explorer 8 中测试的 spans(和 inline-block)。

<h1>Center dynamic box using only css test</h1>
<div class="container">
  <div class="center">
    <div class="center-container">
      <span class="dyn-box">
        <div class="dyn-head">This is a head</div>
        <div class="dyn-body">
          This is a body<br />
          Content<br />
          Content<br />
          Content<br />
          Content<br />
        </div>
      </span>
    </div>
  </div>
</div>

CSS:

.container {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  overflow: hidden;
}

.center {
  position: absolute;
  left: 50%;
  top: 50%;
}

.center-container {
  position: absolute;
  left: -2500px;
  top: -2500px;
  width: 5000px;
  height: 5000px;
  line-height: 5000px;
  text-align: center;
  overflow: hidden;
}

.dyn-box {
  display: inline-block;
  vertical-align: middle;
  line-height: 100%;
  /* Purely asthetic below this point */
  background: #808080;
  padding: 13px;
  border-radius: 11px;
  font-family: arial;
}

.dyn-head {
  background: red;
  color: white;
  min-width: 300px;
  padding: 20px;
  font-size: 23px;
}

.dyn-body {
  padding: 10px;
  background: white;
  color: red;
}

请参见这里的例子

其他回答

最好的方法是使用CSS3。

旧盒子模型(重定向)

显示:盒子和其属性盒子包、盒子平行、盒子东方、盒子方向等已被 flexbox 替换,虽然它们可能仍然工作,但不建议在生产中使用。

#outer { 宽度: 100%; /* Firefox */ 显示: -moz-box; -moz-box-pack:中心; -moz-box-align:中心; /* Safari 和 Chrome */ 显示: -webkit-box; -webkit-box-pack:中心; -webkit-box-align:中心; /* W3C */ 显示: 盒子; 盒子包:中心; 盒子包:中心; } #inner { 宽度: 50%; } <div id="outer"> <div id="inner">Foo foo</div> </div>

根据您的可用性,您也可以使用盒子方向、盒子灵活、盒子方向特性。

现代盒子模型与Flexbox

#outer {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
}

阅读更多关于专注于儿童元素

链接2 链接3 链接4

这解释了为什么盒子模型是最好的方法:

為什麼W3C盒子模型被認為更好?

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

在以前的例子中,他们使用的边界: 0 自动,显示:表和其他答案使用“转换和翻译”。

每个人都知道有一个 <center> 标签,它只是不受 HTML5 支持,但它在 HTML5 中工作。

而且它正在工作,但现在不只是MDN Web Docs,但其他网站建议不要再使用它。 在这里,我可以使用你可以看到MDN Web Docs的笔记。 但无论如何,有这样的方式。

此分類上一篇

中心一个元素,不需要动态高度和宽度的旋转器/父母

没有副作用:它不会限制一个集中元素的宽度低于视门宽度,当使用Flexbox中的边缘在一个集中元素内

position: fixed;
top: 0; left: 0;
transform: translate(calc(50vw - 50%));

垂直 + 垂直中心,如果其高度与宽度相同:

position: fixed;
top: 0; left: 0;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));