Relative units of measurement
A relative unit is measured in terms of some other unit.
The following table shows the relative units:
Unit Identifier | Description |
---|---|
em | Relative to the font size of the element |
ex | Relative to "x-height" of the element's font |
rem | Relative to the font size of the root element |
px | A number of CSS pixels |
% | A percentage of the value of another property |
Working Relative to Font Size
In the following example, the value of the height property is 2em. 2em means that the height of p elements is twice the font size.
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style type="text/css">
p {
background: grey;
color:white;
font-size: 15pt;
height: 2em;
}
</style>
</head>
<body>
<a href="http://java2s.com">Visit the website</a>
<p>I like <span>HTML</span> and CSS.</p>
<p style="font-size:12pt">Font size 12pt.</p>
</body>
</html>
Units That Are Derived from Other Relative Values
In the following example the height is expressed in em units. The em units are derived from the value of the font-size property, which is in rem units.
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style type="text/css">
html {
font-size: 0.2in;
}
p {
background: grey;
color:white;
font-size: 2rem;
height: 2em;
}
</style>
</head>
<body style="font-size: 14pt">
<a href="http://java2s.com">Visit the website</a>
<p>I like <span>HTML</span> and CSS.</p>
</body>
</html>
The rem unit is relative to the font size of the html element. html element is the root element.
html has absolute font size of 0.2 inches. The font-size value is 2rem. 2rem means that the font size will be twice the size of the root element font, which is 0.4 inches. The height property is 2em. 2em means the height is 0.8 inches. p elements's font size is 0.4 inches and height is 0.8 inches.
ex is the current font's x-height. 1ex is approximately 0.5em.
HTML CSS Book
CSS
- CSS Colors
- CSS Lengths
- Absolute units of measurement
- Relative units of measurement
- Working with Pixels
- Working with Percentages
- CSS Unit Calculations
- Using CSS Angles
- Using CSS Times