CSS Property font-size








This property sets the size of the font. The size can be defined as an absolute size, a relative size, a length value, or a percentage value.

Summary

ItemValue
Initial value medium
Inherited Yes.
Version CSS1
JavaScript syntax object.style.fontSize="medium"
Applies to All elements.




CSS Syntax

font-size: length | 
           percentage | 
           larger | 
           smaller | 
           xx-small | 
           x-small |   
           small | 
           medium | 
           large | 
           x-large | 
           xx-larger | 
           inherit 




Property Values

The property values are listed in the following table.

Value Description
xx-small xx-small size
x-small extra small size
small small size
medium medium size. This is default
large large size
x-large extra large size
xx-large xx-large size
smaller A smaller size than the parent element
larger A larger size than the parent element
length A fixed size in px, cm, etc.
% A percent of the parent element's font size
inherit Inherit font size from the parent element

Browser compatibility

font-size Yes Yes Yes Yes Yes

Absolute size

Absolute size sets the text to a specified size. Absolute size is useful when the physical size of the output is known.

Setting the text size with pixels, gives you full control over the text size:

h1 {font-size:40px;} 
h2 {font-size:30px;} 
p {font-size:14px;}

Relative size

Relative size sets the size relative to surrounding elements. Allows a user to change the text size in browsers.

The default size for normal text, like paragraphs, is 16px (16px=1em).

To avoid the resizing problem, we can use em instead of pixels. 1 em is equal to the current font size. The default text size in browsers is 16px. So, the default size of 1em is 16px.

The size can be calculated from pixels to em using this formula: pixels/16=em.

h1 {font-size:2.5em;} /* 40px/16=2.5em */
h2 {font-size:1.875em;} /* 30px/16=1.875em */ 
p {font-size:0.875em;} /* 14px/16=0.875em */

Example

The following code shows using different values to set font-size.

h2 {font-size: 200%;} 
code {font-size: 0.9em;} 
p.caption {font-size: 9px;}
<!DOCTYPE HTML>
<html>
<html>
<head>
<style>
h2 {<!--   w  w w.j  a  v a2 s  .  c  o m-->
    font-family: Georgia, Times, serif;
    font-size: 18px;
}
</style>
</head>
<body>
    <h1>this is a test. </h1>
    <h2>this is a test. </h2>
    <p>this is a test. <strong>this is a test. </strong> 
        this is a test. </p>
    <p>this is a test. </p>
</body>
</html>

Click to view the demo