0
0
CssConceptBeginner · 3 min read

What is ex in CSS: Explanation and Usage

In CSS, ex is a relative length unit that represents the height of the lowercase letter 'x' in the current font. It is used to size elements relative to the font's x-height, which can vary between fonts and styles.
⚙️

How It Works

The ex unit in CSS measures the height of the lowercase letter 'x' in the font currently applied to an element. Think of it like measuring the size of a small letter in your text to decide how big other parts should be. This means the actual size of 1ex changes depending on the font and its style.

Imagine you have different handwriting styles: some letters are tall, some are short. The ex unit adapts to these differences, so your design stays balanced and proportional no matter the font. This makes it useful when you want sizes that relate closely to the text's shape, not just its overall height.

💻

Example

This example shows two boxes sized using ex and em units to highlight the difference. The ex box height matches the x-height of the font, while the em box height matches the full font size.

html
html {
  font-family: Arial, sans-serif;
  font-size: 40px;
}

.box-ex {
  width: 10ex;
  height: 10ex;
  background-color: lightblue;
  margin-bottom: 20px;
}

.box-em {
  width: 10em;
  height: 10em;
  background-color: lightcoral;
}

<body>
  <div class="box-ex">10ex box</div>
  <div class="box-em">10em box</div>
</body>
Output
Two colored square boxes stacked vertically: the top is light blue labeled '10ex box' and smaller in height, the bottom is light coral labeled '10em box' and larger in height.
🎯

When to Use

Use ex when you want element sizes to relate to the height of lowercase letters, which can help keep text and design elements visually balanced. This is especially useful for vertical spacing or aligning elements with text.

For example, if you want a line or border to match the height of text characters or create spacing that feels natural with the font's shape, ex is a good choice. However, because ex varies between fonts and browsers, it is less common than em for general sizing.

Key Points

  • ex measures the x-height of the current font.
  • It changes size depending on font and style.
  • Useful for sizing elements relative to lowercase letter height.
  • Less consistent across browsers than em, so use carefully.
  • Good for vertical alignment and spacing tied to text shape.

Key Takeaways

ex is a CSS unit based on the height of the lowercase 'x' in the font.
It helps size elements relative to the font's x-height for balanced design.
ex varies by font and browser, so test for consistency.
Use ex for vertical spacing or alignment linked to text shape.
For general sizing, em is more commonly used and consistent.