3

How can I vertically center an element between the highest and the lowest characters of another element (ideally only CSS but ok for JS)?

I mean relatively to the characters that are present (the actual text content), not to the line height (which is not responsive to the characters).

The goal is to align an element with the "perceived middle" of a text.

diagram

  • have you tried vertical align? have you tried anything? – Bravo Jul 25 '21 at 08:15
  • What do you want to happen if for example there wasn't the T there, of if there wasn't the g? i.e. are you looking for the vertical center of the font as a whole or only of the characters that are present. – A Haworth Jul 25 '21 at 08:24
  • I've been trying for an hour. Vertical align is relative to the middle of the line height, which is not what I want. – Victor Massé Jul 25 '21 at 08:25
  • If there wasn't the T there, the relative middle would be between the top of the o/g and the bottom of the g. I don't want the middle of the line height, I want it to be relative to the characters that are present. – Victor Massé Jul 25 '21 at 08:29
  • related: https://stackoverflow.com/a/58925003/8620333 – Temani Afif Jul 25 '21 at 09:53

1 Answers1

1

This should help you, you can see the difference in the snippet.

Heights in fonts

* {
  font-family: sans-serif;
}

section {
  float: left;
  margin: 0 10px;
}

div {
  display: flex;
  flex-direction: row;
  align-items: center;
  height: 100px;
}

h1 {
  height: 1em;
  line-height: .8em;
}

h1,
h2 {
  border-top: 1px solid blue;
  border-bottom: 1px solid blue;
  font-size: 40px;
}
<section>
  <p>Height set to 1em</p>
  <div>
    <h1>oTg</h1>
    <svg aria-hidden="true" class="svg-icon iconIndent" width="18" height="18" viewBox="0 0 18 18"><path d="M0 5v8l4.5-4z"></path></svg>
  </div>
</section>
<section>
      <p>Default height</p>
      <div>
        <h2>oTg</h2>
        <svg aria-hidden="true" class="svg-icon iconIndent" width="18" height="18" viewBox="0 0 18 18"><path d="M0 5v8l4.5-4z"></path></svg>
      </div>
</section>
Timothy Alexis Vass
  • 2,526
  • 2
  • 11
  • 30