使标题文本相对于背景容器处于相同位置

时间:2019-07-10 20:06:50

标签: html css alignment

我在父容器中有一个h1标题,因此我希望这样,无论屏幕宽度如何,h1文本始终相对于父容器处于相同位置(即背景为灰色的背景)。

当我减小窗口大小时,灰色的父容器会偏离对齐状态,好像它以比文本向左移动更快的速度向左拉?

我很确定这是可能的,但是这让我有点疯狂,试图找到一种解决方法。

我也必须使用父容器上给出的宽度计算,原因是没有意义。

任何帮助都会很棒。

Codepen:https://codepen.io/emilychews/pen/NZoMbQ

下面的代码段。

body {
  margin: 0;
  padding: 0;
  display: flex;
  height: 100vh;
  width: 100%;
}

.section {
  position: relative;
  display: flex;
  margin: 0 auto; 
  width: 100%;
  padding: 3.583rem 0;
  box-sizing: border-box;
  height: 100vh;
}

.left-background-box {
  height: 100%;
  background: lightblue;
  width: calc(10% + (27.133% - 1rem));
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

h1 {
  font-family: arial;
  font-size: 3rem;
  position: relative;
  left: 65%;
  margin: 1.728rem 0;
  line-height: 4.299rem;
  width: 30rem;
}
<section class="section">
    <div class="left-background-box">
        <h1 class="heading">This is a good two<br>
          Line Title to use
      </h1>
        <h3 class="subheading">Focused on the Issues That Affect You.</h3>
    </div>
</section>

1 个答案:

答案 0 :(得分:1)

.left-background-box宽度以与.heading位置不同的速率变化的原因是,一个具有基于百分比和静态值的宽度计算,而另一个具有{{1 }}属性值仅基于百分比。

如果必须使用特定的left作为calc的宽度,则也应在.left-background-box的{​​{1}}处使用它。您也可以将其简化为left

唯一的区别是您需要进行更多计算才能调整相同的速率,因为.heading嵌套在calc(37.133% - 1rem)内,并且百分比将考虑其父级宽度。但是,如果您有一个全角部分作为两者的父级,则可以使用.heading而不是.left-background-box使用相同的值。您还可以调整“静态”值(这里是vw来调整标题的对齐方式)

这里是一个示例:codepen