How to Set Font Weight in CSS

Introduction

Setting the font weight in CSS allows you to control the thickness or boldness of text. The font-weight property helps create visual hierarchy and emphasis on different parts of your content.

In this tutorial, you'll learn how to set font weight using the font-weight property in CSS. We will explore using both predefined keywords like bold and numeric values to adjust text thickness.

Problem Statement

Create a CSS code that:

  • Adjusts the font weight of text using the font-weight property.
  • Demonstrates different ways to control the weight, using both keywords and numeric values.

Example:

  • Input: A paragraph element with the text "Font Weight Example".
  • Output: The text appears in different font weights based on the applied CSS.

Solution Steps

  1. Use font-weight Property with Keywords: Apply predefined values like normal, bold, or lighter to control the text weight.
  2. Use Numeric Values for Font Weight: Set the font weight using numeric values like 400, 700 for more precise control.

HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Font Weight Example</title>
    <style>
        /* Step 1: Set font weight using predefined keywords */
        .normal-weight {
            font-weight: normal;
        }

        .bold-weight {
            font-weight: bold;
        }

        /* Step 2: Set font weight using numeric values */
        .light-weight {
            font-weight: 300;
        }

        .heavy-weight {
            font-weight: 900;
        }
    </style>
</head>
<body>

    <p class="normal-weight">This text is normal weight (default).</p>
    <p class="bold-weight">This text is bold using font-weight: bold.</p>
    <p class="light-weight">This text is lighter using font-weight: 300.</p>
    <p class="heavy-weight">This text is heavy using font-weight: 900.</p>

</body>
</html>

Output

You can play with the above HTML in Online HTML Editor and Compiler. Here is the output of the above HTML page.:

Explanation

Step 1: Use font-weight with Keywords

  • To set the font weight using keywords like normal or bold, use this CSS:
    .normal-weight {
        font-weight: normal;
    }
    
    .bold-weight {
        font-weight: bold;
    }
    

Step 2: Use font-weight with Numeric Values

  • To control the font weight more precisely, use numeric values between 100 and 900:
    .light-weight {
        font-weight: 300;
    }
    
    .heavy-weight {
        font-weight: 900;
    }
    

Conclusion

Setting the font weight in CSS is simple using the font-weight property. You can use predefined keywords like bold or numeric values like 700 to adjust the text thickness and enhance the visual hierarchy of your content.

Comments