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

时间:2015-09-23 00:44:57

标签: html css header containers center

有一个div(真的是一个标题元素),我看到很多网站现在显示文本内容完美地集中在容器中。所以我正在尝试,但到目前为止,它远远超过了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; }

2 个答案:

答案 0 :(得分:1)

你的margin: 15% auto 0;正是它的顶峰。您需要将所有内容都包含在<div>中,并为此提供以下样式:

&#13;
&#13;
.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;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用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 */
}

DEMO:http://jsfiddle.net/nuoxpmrk/2/

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