CSS Font (Cont.)


Set Font Size with Pixels
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; }
The example above allows Firefox, Chrome, and Safari to resize the text, but not Internet Explorer.

Set Font Size with Em
To avoid the resizing problem with Internet Explorer, many developers use em instead of pixels. The em size unit is recommended by the W3C. 1em 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 */
In the example above, the text size in em is the same as the previous example in pixels. Unfortunately, there is still a problem with IE. When resizing the text, it becomes larger than it should when made larger, and smaller than it should when made smaller.

Use a Combination of Percent and Em
The solution that works in all browsers is to set a default font-size in percent for the body element:
   body { font-size:100%; }
   h1   { font-size:2.5em; }
   h2   { font-size:1.875em; }
   p    { font-size:0.875em; }
Our code now works great! It shows the same text size in all browsers, and allows all browsers to zoom or resize the text!

All CSS Font Properties
The number in the “CSS” column indicates in which CSS version the property is defined (CSS1 or CSS2).

Property Description Values CSS
font
A shorthand property for setting all of the properties for a font in one declaration font-style
font-variant
font-weight
font-size/line-height
font-family
caption
icon
menu
message-box
small-caption
status-bar
1
font-family
A prioritized list of font family names and/or generic family names for an element family-name
generic-family
1
font-size
Sets the size of a font xx-small
x-small
small
medium
large
x-large
xx-large
smaller
larger
length
%
1
font-style
Sets the style of the font normal
italic
oblique
1
font-variant
Displays text in a small-caps font or a normal font normal
small-caps
1
font-weight
Sets the weight of a font normal
bold
bolder
lighter
100
200
300
400
500
600
700
800
900
1


Demonstration
The following demonstration shows how the script of HTML and CSS is displayed on the Web:

     


Review: CSS Fonts
Which is a NOT valid value for the CSS property font-size?
      50%
      2.5em
      15px
      tiny
Result:        




      If I agreed with you, we’d both be wrong.