Relative Lengths
Description
A relative unit is measured in terms of some other unit.
CSS defines a wide range of relative measurements.
The following table shows the relative units that CSS defines and are supported on in mainstream browsers.
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 (assumed to be on a 96dpi display) |
% | A percentage of the value of another property |
Example
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>
<style>
p { <!--from w w w. j a v a2 s.co m-->
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>
Example 2
The following code shows how to compare height setting in inch and pixel.
<html>
<head>
<title>Pixels to Inches</title>
<style type='text/css'>
div {<!--from w w w.j a v a 2 s . c om-->
background: #000;
border: 1px solid rgb(128, 128, 128);
color: white;
font: 9px monospace;
margin: 15px;
text-align: center;
}
div#inches {
width: 1in;
height: 1in;
}
div#pixels {
width: 96px;
height: 96px;
}
</style>
</head>
<body>
<div id='inches'><-- 1 Inch --></div>
<div id='pixels'><-- 96 Pixels --></div>
</body>
</html>
Pixel values
An easy to set the length is to use pixel value. 1 pixel is 1/96th of an inch. The following code set the font size and width in pixel value.
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
p { <!-- w w w . j ava 2s. com-->
background: grey;
color:white;
font-size: 20px;
width: 200px;
}
</style>
</head>
<body>
<a href="http://java2s.com">Visit the website</a>
<p>I like <span>HTML</span> and CSS.</p>
</body>
</html>
Percentage values
You can express a unit of measurement as a percentage of another property value. You do this using the % (percent) unit.
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
p { <!--from w ww .j a va 2 s .c om-->
background: grey;
color:white;
font-size: 200%;
width: 50%;
}
</style>
</head>
<body>
<a href="http://java2s.com">Visit the website</a>
<p>I like <span>HTML</span> and CSS.</p>
</body>
</html>
One good feature for percentage value is that the value is updating as you resize the browser window.