Center an element between the highest and the lowest characters

Viewed 60

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

1 Answers

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>

Related