Monday, 28 February 2011

CSS: Custom fonts with CSS3 (@font-face)

   


CSS3 is being slowly introduced in our beloved web design world. I say 'slowly' because in reality some of the new properties are already implemented in the latest web browser versions.
One is the @font-face rule. Interestingly enough, I've published something about custom fonts in web pages using JavaScript. With @font-face everything is easier.
Let's see how it works!

The font
Before CSS3, web developers couldn't add custom fonts to their web pages, unless they used some sort of tricks (like the one explained in my previous post). With CSS3, you only need to copy your fonts to the web server. Because at the moment, Internet Explorer supports only .eot font files, we will need to upload two files: the .ttf and the .eot.

The style
Now we need to use the @font-face rule. Just add the following style to the head section of your page:
<style type="text/css">
@font-face
{
font-family: CustomFont;
src: url('my_font.ttf'),
     url('my_font.eot') format("opentype"); /* IE */
}

div
{
font-family:CustomFont;
}
</style>
Ok, let me explain it.
In the above snippet, we assume that the custom font file are my_font.ttf and my_font.eot. Our cutom font is called CustomFont and we set the font family for every div container to that font.

The HTML
If you add to the body section of your page, the following HTML code:
<div>Hello! This is my new font!</div>
you will see that the above txt is rendered with the new font.

Features
In order to further customize your CustomFont, we can add font descriptors inside the @font-face rule. The following list explains the various options:

Descriptor Values Description
font-family name Required. Defines a name for the font
url URL Required. Defines the URL to the font file
font-stretch normal
condensed
ultra-condensed
extra-condensed
semi-condensed
expanded
semi-expanded
extra-expanded
ultra-expanded
Optional. Defines how the font should be stretched. Default is "normal"
font-style normal
italic
oblique
Optional. Defines how the font should be styled. Default is "normal"
font-weight normal
bold
100
200
300
400
500
600
700
800
900
Optional. Defines the boldness of the font. Default is "normal"
unicode-range unicode-range Optional. Defines the range of UNICODE characters the font supports. Default is "U+0-10FFFF"

Compatibility
@font-face is compatible with IE, Firefox, Chrome, Opera and Safari. As said before IE needs the font file to be in .eot format.

Start playing around with these new feature. I'm actually quite enjoying it, and possibly I will talk about further CSS3 new stuff in the near future.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.