What is ex in CSS: Explanation and Usage
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 {
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>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
exmeasures 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.ex varies by font and browser, so test for consistency.ex for vertical spacing or alignment linked to text shape.em is more commonly used and consistent.