Center first headline, make second headline start where first headline starts

Viewed 42

I have a primary and a secondary headline. The primary headline is longer and should be centered. The second headline should start exactly where the first one starts. So if this is my setup:

        <h1 className="sofortcheck__headline--mobile">
          Check your situation for free
        </h1>
        <h2 className="sofortcheck__subheader--mobile">
          Only <span>2 minutes</span>
        </h2>

I want both of those lines to start at exactly the same spot (on all devices) after I center the first line.
Is there a way to do this in pure CSS?
So far I can only think of getting the left offset in JavaScript and then setting that for the second headline, but I feel like there should be a way to achieve this in CSS only.
When I center both elements the second one starts later than the first one because it's shorter. When I use px margins it doesn't work for different screens.

2 Answers

This is fairly easy to do in the markup. You left-justify both the headline and subheadline in an element, then center that element relative to your page.

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>

CSS-Grid can do that.

* {
  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>

Related