Using the combination of Percentage and Em in CSS


We can use a combination of percentage and em to specify the font-size of elements for better compatibility of font. This allows us to have uniform text across different browsers. Both percentage and em are relative measurements.

Syntax

The syntax of CSS font-size property is as follows. The below works for both the percentage and em units in place of value. Also, other length units can also be set −

Selector {
   font-size: /*value*/
}

Example

The following example illustrate how CSS font-size property can be set. First, we have set the <body> font using the font-size property in percentage −

body {
   font-size: 80%;
}

The font size for the <p> element is set with the em unit −

p {
   font-size: 2em;
}

Let us see the example −

<!DOCTYPE html>
<html>
<head>
   <style>
      body {
         font-size: 80%;
      }
      p {
         font-size: 2em;
      }
      span {
         font-size: 4em;
         font-style: italic;
      }
   </style>
</head>
<body>
   <p>Reading <span>source code</span> written by others gives you opportunity to criticize the mistakes done in writing that code</p>
</body>
</html>

Example

The following example illustrate how CSS font-size property can be set. First, we have set the

font using the font-size property in percentage −

div {
   font-size: 120%;
}

The font size for the

element is set with the em unit −

p {
   font-size: 2em;
}

Let us see the example −

<!DOCTYPE html>
<html>
<head>
   <style>
      div {
         font-size: 120%;
      }
      p {
         font-size: 2em;
      }
   </style>
</head>
<body>
   <h3>Demo Heading</h3>
   This is example text.
   <div>
      Examples are easier to understand with practical implementation
      <p>This is another text just to display different ways to set font size in CSS.</p>
   </div>
</body>
</html>

Updated on: 02-Jan-2024

217 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements