Search code examples
htmlcss

How to include a font .ttf using CSS?


I want to include a global font for my page. I downloaded a .ttf file, and included it in my CSS, but my font won't change.

Here's my code:

@font-face {
    font-family: 'oswald';
    src: url('/font/oswald.regular.ttf');
}

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
    margin:0;
    padding:0;
    border:0;
    font-size:100%;
    font:inherit;
    font-family: oswald;
    vertical-align:baseline
} 

Where did I go wrong?


Solution

  • Only providing a .ttf file for web fonts won't be good enough for cross-browser support. The best possible combination at present is using a combination:

    @font-face {
        font-family: 'MyWebFont';
        src: url('webfont.eot'); /* IE9 Compat Modes */
        src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
             url('webfont.woff') format('woff'), /* Modern Browsers */
             url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
             url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
    }
    

    This code assumes you have .eot , .woff , .ttf and svg format for you webfont. To automate all this process , you can use a web font generator like Font Squirrel or Transfonter.

    Also, modern browsers are shifting toward the .woff font type, so you can probably do this, too:

    @font-face {
        font-family: 'MyWebFont';
        src: url('myfont.woff') format('woff'), /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
             url('myfont.ttf') format('truetype'); /* Chrome 4+, Firefox 3.5, Opera 10+, Safari 3—5 */
    }  
    

    Read more here: https://css-tricks.com/snippets/css/using-font-face/

    For browser support: Can I Use fontface