HTML Dog

Skip to navigation

Superscript and Subscript

In the olden days, the sup and sub tags were used to present something in superscript or subscript but in this modern day and age we leave presentation up to CSS.

You could just use the CSS property vertical-align with the value super or sub or even a length to achieve rudimentary superscript and subscript, but the problem is that in a paragraph, those lines with superscript or subscript text will alter the height of that line, resulting in an inconsistently spaced paragraph.

Step 1: The HTML

The way to get around this problem is to nudge the superscript and subscript out of the whole flow a little bit so if you have the following HTML:


<p>My name is Doctor Womac and I am going to teach you all about chemical formulae.
A chemical formula is a way to describe the chemical elements that make up a particular chemical compound.
It consists of chemical symbols to covey the elements and numbers to show the number of atoms of each element.
H<span class="atoms">2</span>S0<span class="atoms">4</span> is the chemical formula for sulphuric acid, for example.
The charge of an ion can be displayed in superscript, such as Au<span class="charge">2+</span>.
This concludes my lesson.
I must rush off home now because I have a problem with some radioactive phosphate.</p>

Step 2: Vertically aligning

You can achieve the desired effect with the following CSS:


body { font: 80% "Times New Roman", Times, serif }

p { line-height: 1.5 }

.charge {
	position: relative;
	bottom: 0.5em;
	color: red;
	font-size: 0.8em;
}

.atoms {
	position: relative;
	top: 0.3em;
	color: blue;
	font-size: 0.8em;
}

Whereas vertical-align will mess about with the line-height (try changing the line-height of the paragraph to 1 and replacing bottom: 0.5em with vertical-align: 0.5em), simply pushing the required elements up or down a bit with top or bottom makes things much easier and neater.