How to Specify Different Font Weights for the Same Custom Font in CSS?

In CSS, you can specify different font-weight for the same custom font by adding each one to a separate @font-face rule, for example, like so:

@font-face {
  font-family: 'Roboto';
  src: url('Roboto-Regular.ttf') format('truetype');
  font-weight: normal;
}

@font-face {
  font-family: 'Roboto';
  src: url('Roboto-Light.ttf') format('truetype');
  font-weight: 300;
}

@font-face {
  font-family: 'Roboto';
  src: url('Roboto-Bold.ttf') format('truetype');
  font-weight: bold;
}

/* ... */

As you can see in the example above, you need to keep the same font-family value for each @font-face rule, and specify different font sources and weights for that font that you wish to support. After doing so, you will be able to use that font-family with any of the font-weight you added to @font-face rules, like so:

body { font-family: 'Roboto'; font-weight: normal; }

h1, h2, h3 { font-family: 'Roboto'; font-weight: bold; }

.sub-heading { font-family: 'Roboto'; font-weight: 300; }

Please note that for the font-weight definitions you don't add in the @font-face rules, the browser will substitute them with a nearby weight.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.