Wednesday, April 4, 2012

How to add Custom Fonts in CSS

Today, I was searching the internet to use custom fonts on my website. I got a few links here and there that spoke about how to add fonts that are not supported by default in any browser, but I didn't find the articles convincing. So I planned to write my own article elaborating the use of such fonts on websites.

Basically, we will make use of the @font-face property to load a custom font from the local folder in order to use it. The syntax is as follows:

@font-face { 
font-family: font-name; 
src: url('font-name.ttf'); 

Where font-name is the name of the font in your local folder. You need to ensure whether the path of the font is correct (In this example, the font file(s) is assumed to reside in the same folder as that of the CSS file). This causes the CSS to load the font in your browser so that you can use the font just using the font-family property anywhere throughout the page.

As there has been constant wars among browsers with respect to CSS, we need to use more types of the same font to ensure cross-browser compatibility. The following formats will be required for the same:

EOT – Embedded Open Type
OTF – Open Type Format
WOFF – Web Open Font Format
SVG – Scalable Vector Graphics

Once you have obtained the .EOT, .OTF, .WOFF and .SVG formats of the same font, you can modify the @font-family property as follows:

@font-face { 
font-family: 'font-name'; 
src: url('font-name.eot'); 
src: ('font-name.woff') format('woff'), url('font-name.ttf') format('truetype'), url('font-name.svg') format('svg'); 
font-weight: normal; 
font-style: normal; 

We add the extra properties font-weight and font-style to ensure that the font is shown in the same manner in all the browsers.

You may now be thinking of how to obtain various formats of the same font. There are some free online generators that can help generate the other formats once toy provide the .TTF or the .OTF file. There are two free online services that generate the necessary formats of the same font: FontSquirrel and Font2Web.

No comments:

Post a Comment