Mike Flynn
Mike Flynn

Reputation: 24325

Vertically Center Sub and Super Script in HTML

Is there a way to vertically center a sub and super script at the same time? I would like the "e" vertically centered with the "r".

<span><sup>e</sup><sub>r</sub>Team 1</span>

enter image description here

Upvotes: 1

Views: 1678

Answers (4)

Olu
Olu

Reputation: 77

I came across the solutions provided here while trying to resolve symbols for a science subject. I decided to use in-line style method to avoid conflict with other parts of the html and modified the font-size. Below works fine. It aligns the sup and sub tag vertically wothout space in-between

<span style="display: flex;">Ca<span style="display: flex; align-items: center; flex-direction: column; font-size: 0.75rem;"><sup>40</sup><sub>20</sub></span></span>

Hopefully there may be a better helper somewhere as I continue for a search

Upvotes: 0

Narek-T
Narek-T

Reputation: 1918

Just one more solution. Note this will work only when you have 1 letter in your sub or superscript.

span {
  font-size: 30px;
  position: relative;
  padding-left: 0.5em
}
sup,
sub {
  position: absolute;
  left: 0;
  line-height: 0.8;
  font-size: .6em;
}
sup {
  top: 0;
}
sub {
  bottom: 0;
}
<span><sup>e</sup><sub>r</sub>Team 1</span>

Upvotes: 1

Rick Hitchcock
Rick Hitchcock

Reputation: 35680

If you don't mind a monospace font for the [sub][super]scripts, you could do the following:

span {
  font: 20px verdana;
}

sup, sub {
  font-family: monospace;       /* make letters same width so the transform aligns them properly */
}

sup + sub {
  display: inline-block;        /* transform doesn't work on inline elements */
  transform: translateX(-100%); /* move backwards */
}
<span><sup>e</sup><sub>r</sub>Team 1</span>

Upvotes: 1

Paulie_D
Paulie_D

Reputation: 115365

Well, there is but you pretty much have to strip away all the default stylings that are inherent to these tags. So you might as well use spans.

You'll also need a wrapper so that you can arrange them how you want...I've used flexbox but I'm sure there are other methods.

body {
  font-size: 36px;
  text-align: center;
}
span.column {
  flex-direction: column;
  display: inline-flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
  vertical-align: text-top;
}
sup,
sub {
  top: 0;
  bottom: 0;
  line-height: 1;
  font-size: .5em;
}
<span>
  <span class="column"><sup>e</sup><sub>r</sub></span>
Team 1
</span>

Upvotes: 2

Related Questions