CSS Font Size

The CSS font-size property is used to define the size of text content. You can set the font size using absolute units like pixels (px) for a fixed size, or relative units like em, rem, vw, vh, or percentages for responsive and scalable designs.

Font size plays a crucial role in readability and visual hierarchy, so choosing an appropriate size is important for effective communication on your web pages.


Using Pixels (px)

The font-size property can be specified using pixels (px). Pixels provide an absolute measurement, meaning the font size will have a fixed value regardless of the device or screen resolution

Example
        
            p {
   font-size: 16px;
}
        
    

This sets the font size of <p> elements to 16 pixels.


Using Relative Units

CSS provides several relative units for specifying font size relative to other elements. These units are helpful for creating responsive designs that adapt to different screen sizes.


Using Percentages (%)

The font-size property can also be specified using percentages. Percentages are relative to the font size of the parent element.

        
            .container {
    font-size: 120%;
}
        
    

This sets the font size of elements with the class "container" to 120% of their parent element's font size.

It's important to consider factors such as readability, accessibility, and responsive design when choosing font sizes. Testing and adjusting font sizes across different devices and screen sizes can help ensure that your text content is legible and visually pleasing for your users.


Font Size Example

Try yourself
        
            <html>
<head>
    <style>
        html {
            font-size: 18px; /* Sets the base font size for the entire HTML document. 1rem = 16px.
                                Note: The font-size value of the HTML element will not affect the em value
                                because the font-size value is defined in the body element. */
        }

        body {
            font-size: 16px; /* Sets the base font size for the body element. 1em = 16px. */
        }

        div.wrapper {
            font-size: 20px; /* Sets the font size for the elements inside the div
                                with the class "wrapper". 1em = 20px for the elements inside this div. */
        }

        h1 {
            font-size: 3em; /* Sets the font size for the h1 heading element.
                               3em = 48px (assuming the base font size is 16px). */
        }

        div.wrapper h1 {
            font-size: 3em; /* Overrides the font size for the h1 heading element when it is inside
                               the div with the class "wrapper". 3em = 60px (assuming the base font size is 20px). */
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <h1>This is a heading</h1>
    </div>
</body>
</html>