即使溢出容器也能保持元素居中

Keep element centered even when overflowing its container

我在下面的代码片段中重现了我的问题:如果您将其设为 整页 并拖动以减小 window 和 h1 的水平尺寸当元素超出其容器的边界时,它不会保持居中。

这是一个视觉效果:

请注意,在它超出其容器边界后,它只是保持左对齐。 我希望它保持居中。有简单的 CSS 修复吗?

@import url( 'https://necolas.github.io/normalize.css/latest/normalize.css' );
* {
  outline: 1px solid red;
}
html, body {
  overflow: hidden;
  height: 100%;
  text-align: center;
}
h1 {
  margin: 0;
  color: #f3f3f3;
}
.v-cntr {
  position: relative;
  top: 50%;
  transform: translateY( -50% );
}
.hdg-wrap {
  font-size: 5.5rem;
  position: absolute;
  top: 48%;
  right: 0;
  bottom: 0;
  left: 0;
  transform: translateY( -100% );
  z-index: -1;
}
<header class="v-cntr">              <!-- << v-cntr = vertically center -->

  <!-- ----------------------- HEADING WRAPPER ------------------------ -->
  <div class="hdg-wrap">
    <h1>RIDE</h1>
  </div>

  <!-- ------------------------ IMAGE WRAPPER ------------------------- -->
  <div class="img-wrap">
    <img src="http://svgshare.com/i/xL.svg" alt="Logo">
  </div>
</header>

我尽量不改变 HTML

的结构

编辑: 我得到的答案试图将图像而不是其背后的文本居中。我可以看到混乱,因为两者都偏离了中心。我要重申:我主要关心的是保持 h1('ride' 文本)元素在 window 缩小时居中。

您可以重置 .img-wrap 的文本对齐方式,并使用此 CSS.

将图像居中
.img-wrap {
  text-align: initial;
  position: relative;
}
.img-wrap img {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

评论后添加:您可以将相同的原则应用于 h1。因为它的父级已经绝对定位了,所以我没有改变它,只是添加了

h1 {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

这是完整的片段:

@import url('https://necolas.github.io/normalize.css/latest/normalize.css');
* {
  outline: 1px solid red;
}

html,
body {
  overflow: hidden;
  height: 100%;
  text-align: center;
}

h1 {
  margin: 0;
  padding: 0;
  color: #eee;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.v-cntr {
  position: relative;
  top: 50%;
  transform: translateY( -50%);
}

.hdg-wrap {
  color: #fff;
  opacity: 0.5;
  font-size: 5.5rem;
  position: absolute;
  top: 48%;
  right: 0;
  bottom: 0;
  left: 0;
  transform: translateY( -100%);
  z-index: -1;
}

.img-wrap {
  text-align: initial;
  position: relative;
}

.img-wrap img {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}
<header class="v-cntr">
  <!-- << v-cntr = vertically center -->

  <!-- -- - - - - - - - - - - - - - HEADING - - - - - - - - - - - - - - -->
  <div class="hdg-wrap">
    <!-- << hdg-wrap = heading wrapper -->
    <h1>RIDE</h1>
  </div>

  <!-- -- - - - - - - - - - - - IMAGE WRAPPER - - - - - - - - - - - - - -->
  <div class="img-wrap">
    <img src="http://svgshare.com/i/xL.svg" alt="Logo">
  </div>
</header>