转换后继续文档流:translateY(-50%)

时间:2019-07-01 23:59:03

标签: css css-position css-transforms

我需要在CSS转换之后缩小差距:translateY(-50%),以使内容自然流动。

我尝试了其他方法,但是无法将元素向上移动其自身高度的50%。负边距百分比是基于窗口的高度,因此这似乎不是一个选项,我也不能在以下元素上设置负边距,因为它需要基于页眉的高度。

HTML:

<div class="header">
  <div class="featured-image">
    <!-- this is in place of the featured image -->
  </div>

  <div class="title-container">
    <h1>Title<br />goes<br />here</h1>
  </div>
</div>

<div class="article-body">
  <p>There is too much space above class="article-body". I want the content to flow on naturally after class="title-container", however using translateY is purely visual so an alternate method of moving the yellow block up by 50% of its own height is necessary.</p>
</div>

CSS:

.header {
  width: 100%.
  position: relative;
}

.featured-image {
  width: 100%;
  height: 200px;
  background-color: blue;
}

.title-container {
  width: 50%;
  margin: 0 auto;
  transform: translateY(-50%);
  background-color: yellow;
}

JS小提琴:

https://jsfiddle.net/robertirish/tyh18orq/16/

可能只有使用Javascript才能实现,但是用纯CSS做到这一点非常好,因为JS和媒体查询很难实现。

谢谢。

1 个答案:

答案 0 :(得分:-1)

使用transform: translateY(-50%)代替使用margin-top: -25vh
这会将.title-container放在同一位置,但保持.article-body在其下方:< / p>

.header {
  width: 100%.
  position: relative;
}

.featured-image {
  width: 100%;
  height: 200px;
  background-color: blue;
}

.title-container {
  width: 50%;
  margin: 0 auto;
  /*transform: translateY(-50%);*/
  margin-top: -25vh;
  background-color: yellow;
}
<div class="header">
  <div class="featured-image">
    <!-- this is in place of the featured image -->
  </div>
  
  <div class="title-container">
    <h1>Title<br />goes<br />here</h1>
  </div>
</div>

<div class="article-body">
  <p>There is too much space above class="article-body". I want the content to flow on naturally after class="title-container", however using translateY is purely visual so an alternate method of moving the yellow block up by 50% of its own height is necessary.</p>
</div>