垂直居中 H1,背景图像为 100%



我正在尝试在具有背景图像的div中垂直对齐H1。

尝试了这种方法,我发现:https://jsfiddle.net/vdqdpyc0/12/

但是发现只有当我专门向div 添加 px 高度或为任一元素添加填充时,横幅的全高才可见。这意味着当我调整大小时,横幅上方和下方都有很多空白。如果背景打算重复,这不会成为问题,但事实并非如此。

最终产品需要看起来像这样。

html,
body {
  height: 100%;
}
.outer-wrapper {
  background: url("http://paulmason.name/media/demos/full-screen-background-image/background.jpg") no-repeat center center;
  background-size: cover;
  max-height: 360px;
  height: 100%;
}
.inner-wrapper {
  display: table;
  width: 100%;
  height: 100%;
}
.header-wrapper {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
h1 {
  color: #fff;
}
<div class="outer-wrapper">
  <div class="inner-wrapper">
    <div class="header-wrapper">
      <h1>
        Vertically aligned text
      </h1>
    </div>
  </div>
</div>

我可以减少各种响应观点的填充,但我认为必须有一种更简化的方式。

如今,使用 flexbox 可以更轻松地实现这一点,例如

html,
body {
  height: 100%;
}
.outer-wrapper {
  background: url("http://paulmason.name/media/demos/full-screen-background-image/background.jpg") no-repeat center center;
  background-size: cover;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
h1 {
  color: #fff;
}
<div class="outer-wrapper">
  <div class="inner-wrapper">
    <div class="header-wrapper">
      <h1>
        Vertically aligned text
      </h1>
    </div>
  </div>
</div>

示例:https://jsfiddle.net/0yxctLne/

你可以为此使用弹性框。这是一个非常简单的弹性框指南。对于您的问题,应该足以通过

display: flex;
flex-direction: column;
justify-content: center;
到 H1 标签周围的元素

,如果周围的元素与您希望 H1 标签居中的空间的高度和宽度相同。这会将主轴定义为垂直(读取:列),然后沿主轴将所有内容居中。如果需要,您还可以添加

align-items: center;

使文本沿十字轴居中(如水平方向)。

你需要这样的东西吗?弹性框是一个很好的方法:

.header-wrapper {
  background: url("http://paulmason.name/media/demos/full-screen-background-image/background.jpg") no-repeat center center;
  background-size: cover;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}
h1 {
  color: #fff;
}
<div class="outer-wrapper">
  <div class="inner-wrapper">
    <div class="header-wrapper">
      <h1>
        Vertically aligned text
      </h1>
    </div>
  </div>
</div>

小提琴

最新更新