CSS @font-face Rule

CSS @font-face Rule

CSS @font-face Rule

The @font-face The rule in CSS allows you to define and use custom fonts in your web projects without relying on standard system fonts.

1. Basic Syntax

@font-face { font-family: 'CustomFont'; src: url('customfont.woff2') format('woff2'); }

✅ This loads customfont.woff2 and makes it available as "CustomFont" in CSS.

2. Using the Custom Font

After defining the font, you can apply it like this:

body { font-family: 'CustomFont', sans-serif; }

✅ The custom font will be used, with sans-serif as a fallback.

3. Specifying Multiple Font Formats

Different browsers support different font formats. To ensure compatibility, define multiple formats:

@font-face { font-family: 'CustomFont'; src: url('customfont.woff2') format('woff2'), url('customfont.woff') format('woff'), url('customfont.ttf') format('truetype'); }

✅ Uses WOFF2 first (best for web), then WOFF, and finally TTF.

4. Adding font-display for Better Performance

@font-face { font-family: 'CustomFont'; src: url('customfont.woff2') format('woff2'); font-display: swap; }

✅ Ensures text appears immediately with a fallback font while the custom font loads.

5. Using Different Font Weights & Styles

@font-face { font-family: 'CustomFont'; src: url('customfont-regular.woff2') format('woff2'); font-weight: normal; } @font-face { font-family: 'CustomFont'; src: url('customfont-bold.woff2') format('woff2'); font-weight: bold; }

✅ Defines both normal and bold weights for better styling control.

6. Best Practices

Use WOFF2 format for modern browsers (smaller file size, better compression).
Always include a fallback font in font-family.
Use font-display: swap; to avoid a "flash of invisible text" (FOIT).
Host fonts locally instead of relying on third-party services (better performance & privacy).

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close