首个标题居中,使第二个标题从第一个标题开始。

3
我有一个主标题和一个次级标题。 主标题更长,应该居中。 第二个标题应该从第一个标题开始的地方开始。 所以如果这是我的设置:
        <h1 className="sofortcheck__headline--mobile">
          Check your situation for free
        </h1>
        <h2 className="sofortcheck__subheader--mobile">
          Only <span>2 minutes</span>
        </h2>

在我居中第一行后,我希望这两行文字的开头(在所有设备上)都正好处于同一位置。
有没有纯CSS的方法可以实现?
我目前只能想到使用JavaScript获取左侧偏移量,然后为第二个标题设置该值,但我觉得应该有一种仅使用 CSS 就可以实现的方法。
当我将两个元素都居中时,第二个元素比第一个元素晚开始,因为它更短。 当我使用像素边距时,它不能适用于不同的屏幕。

2个回答

3

在标记语言中,这个操作非常容易实现。您可以将标题和副标题都左对齐到一个元素中,然后将该元素相对于您的页面居中对齐。

h1 { font-size: 0.75em; }
h2 { font-size: 0.5em; }

.headline-container {
  display: flex;
}

.headline {
  display: inline-block;
  margin: 0 auto;
}
<div class="headline-container">
 <div class="headline">
    <h1>The primary headline which is longer and determines the centering.</h1>
    <h2>The subheadline which is left-justified to the primary.</h2>
  </div>
</div>


1
太棒了!非常感谢。 由于使用边距版本来将标题 div 居中的方法不起作用,我不得不在 headline-container 中使用 justify-content: center。 但这正是我一直寻找的。 - Nickfis
1
“margin”方法依赖于“display: flex”,因此根据您的标记和运行的浏览器,可能会有一些特殊情况。不过,您是正确的,“justify-content”是一个很好的备选方案! - D M

2
CSS-Grid可以实现这一点。

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

 ::before,
 ::after {
  box-sizing: inherit;
}

body {
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  position: relative;
  align-items: center;
}

body::before {
  content: "";
  position: absolute;
  left: 50%;
  height: 100vh;
  width: 1px;
  background: green;
}

.sofortcheck__headline--mobile {
  grid-column: 2;
  border: 1px solid red;
}

.sofortcheck__subheader--mobile {
  grid-column: 2;
  grid-row: 2;
  border: 1px solid grey;
}
<h1 class="sofortcheck__headline--mobile">
  Check your situation for free
</h1>
<h2 class="sofortcheck__subheader--mobile">
  Only <span>2 minutes</span>
</h2>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接