在相对定位 div 的 100% 宽度内垂直和水平居中 div

Centering div both vertically and horizontally inside of 100% width relatively positioned div

有一个 div(实际上是一个 header 元素),最近我看到很多网站都在容器内完美地居中显示文本内容。所以我正在尝试,但到目前为止,它离 div 的顶部比中心还远。示例在这里:http://jsfiddle.net/nuoxpmrk/

HTML:

<header class="entry-header" style="background: url(https://thecleverroot.com/wp-content/uploads/header-hudson-valley-foie-gras.jpg ) no-repeat top center!important; background-size: cover!important;">
  <section class="entry-caption">
    <h1 class="entry-title">Title Goes Here</h1><p class="entry-subtitle">This is a Subtitle</p> <p class="entry-credits">Written by: JS Fiddle</p>
  </section>
</header>

CSS:

.entry-header { position: relative; width: 100%; height: 640px; color: #FFF; }
.entry-caption { margin: 15% auto 0; padding: 32px; text-align: center; width: 100%; }
.entry-caption p.entry-subtitle { font-size: 18px; line-height: 1.25; text-transform: none; }
.entry-caption h1.entry-title { font-size: 38px; line-height: 1.25; }
.entry-caption p.entry-credits { font-size: 14px; line-height: 1; margin-bottom: 1em; text-transform: uppercase; }

您的 margin: 15% auto 0; 使它名列前茅。您需要将所有内容包装在 <div> 中,并为其提供以下样式:

.entry-header {
  position: relative;
  width: 100%;
  height: 640px;
  color: #FFF;
}
.entry-caption {
  padding: 32px;
  text-align: center;
  width: 100%;
}
.entry-caption p.entry-subtitle {
  font-size: 18px;
  line-height: 1.25;
  text-transform: none;
}
.entry-caption h1.entry-title {
  font-size: 38px;
  line-height: 1.25;
}
.entry-caption p.entry-credits {
  font-size: 14px;
  line-height: 1;
  margin-bottom: 1em;
  text-transform: uppercase;
}
.center {
  width: 100%;
  height: 180px;
  position: absolute;
  top: 50%;
  left: 0;
  margin-top: -90px;
  overflow: hidden;
}
<header class="entry-header" style="background: url(https://thecleverroot.com/wp-content/uploads/header-hudson-valley-foie-gras.jpg ) no-repeat top center!important; background-size: cover!important;">
  <section class="entry-caption">
    <div class="center">
      <h1 class="entry-title">Title Goes Here</h1>
      <p class="entry-subtitle">This is a Subtitle</p>
      <p class="entry-credits">Written by: JS Fiddle</p>
    </div>
  </section>
</header>

您可以使用 CSS Flexbox 使这一切变得非常简单。只需要加三行代码,还可以去掉一堆代码。

无论屏幕垂直或水平调整大小,居中项目将保持居中。

HTML(无变化)

CSS

.entry-header { 
    display: flex; /* establish flex container */
    justify-content: center; /* center child element (<section>) horizontally */
    align-items: center; /* center child element (<section>) vertically */

    /* No further changes */

    position: relative;
    width: 100%;
    height: 640px;
    color: #FFF;
}

.entry-caption { 
    /* margin: 15% auto 0; don't need this */
    /* padding: 32px; don't need this */
    text-align: center; 
    /* width: 100%; don't need this */
}

演示:http://jsfiddle.net/nuoxpmrk/2/

请注意,所有主要浏览器都支持 flexbox,except IE < 10