Creating Superscript and Subscript Text with CSS: `vertical-align`

Learn how to create superscript and subscript text using CSS's `vertical-align` property. This tutorial explains how to achieve this effect, compares it to using HTML's `` and `` tags, and provides practical examples for styling mathematical and scientific notations. Enhance your CSS text styling.



Creating Superscript and Subscript Text with CSS

Understanding Superscript and Subscript

Superscript and subscript text are smaller text that appears slightly above (superscript) or below (subscript) the normal baseline. In HTML, these are typically created using the ` and `` tags, respectively. These are often used for mathematical formulas, chemical formulas, and footnotes. CSS offers an alternative way to achieve a similar visual effect using the `vertical-align` property.

Using `vertical-align` for Superscript and Subscript

The `vertical-align` property controls the vertical alignment of an element's content. While its primary purpose isn't specifically for superscript and subscript, setting it to `super` or `sub` creates the desired visual effect. However, this approach requires additional styling (like font size) to achieve the same look as HTML's `` and `` tags.

`vertical-align` Property Values

  • baseline (default): Aligns the element's baseline with its parent's baseline.
  • super: Creates a superscript effect (raises the text).
  • sub: Creates a subscript effect (lowers the text).

`vertical-align` Syntax

The syntax is:

vertical-align: baseline | super | sub;

Examples: Superscript and Subscript

These examples demonstrate creating superscript and subscript text using `vertical-align`. You would need to include the corresponding HTML (e.g., span elements) and CSS to see the effects.

Example 1: Superscript

This shows how to create superscript text (often used for exponents or footnotes).

CSS Code

span.super {
  vertical-align: super;
  font-size: 0.8em; /* Adjust size as needed */
}

Example 2: Subscript

This shows how to create subscript text (often used for chemical formulas).

CSS Code

span.sub {
  vertical-align: sub;
  font-size: 0.8em; /* Adjust size as needed */
}