How to add a custom font into Html using CSS?

Dung Do Tien May 27 2020 582

I have a small website, I don't want to use some default font family of browser such as Arial, Roboto....

I have download Nunito font from google but How to import a custom font into Html using CSS? and what is the best way to do and help improve the performance load time of the website?

Thanks for any ideas.

Have 1 answer(s) found.
  • M

    Marry Christ May 27 2020

    1. How to add custom font into Html using CSS?

    Answer: using @font-face of css3 to import font. See an example below:

    @font-face {
        font-family: 'Roboto';
        src: url('Roboto-Regular.eot');
        src: local('Roboto Regular'), 
            url('../font/Roboto-Regular.eot?#iefix') format('embedded-opentype'), 
            url('../font/Roboto-Regular.woff') format('woff'), 
            url('../font/Roboto-Regular.ttf') format('truetype'), 
            url('../font/Roboto-Regular.svg') format('svg');
        font-weight: 400;
        font-style: normal;
    } 
    

    font-family: You can type any name you want.

    url: Set to the relative path of your site.

    How to use this custom font?

    - You can use normally like the default font. For example:

    h1{
       font-family: "Roboto";
    } 

     

    2. How to customize load font for fast performance?

    we have 2 problems that need to resolve with load a custom font.

    2.1 Block display text while loading the font file

    Text of your web page will not display while loading custom font file, You need display text with default font while loading custom font. To resolve this problem you can add font-display: swap property CSS into your custom font:

    @font-face {
        font-family: 'Roboto';
        src: url('Roboto-Regular.eot');
        ..................................
        font-style: normal;
        font-display: swap;
    } 
    

    2.2 Preload font file.

    If you preload the font file, you will help increase the performance of your website. You can see an example below :

    <link rel="preload" href="../font/Roboto-Regular.woff" as="font" type="font/woff" crossorigin /> 

    Push this code into the inside of the <head> tag.

    You can refer the article below for more custom CSS performance:

    Add css to html for best performance.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close