CSS Font Size - px, em, rem, vw, vh

In CSS, there are several units you can use to define font sizes. Each unit has its own characteristics and use cases. Here’s an overview of some common units for specifying font sizes:

Pixels (px):

  • Pixels are an absolute unit of measurement and are commonly used for font sizing.
  • 1 pixel is equal to one dot on the screen.
  • Font sizes in pixels don’t change with the user’s settings, making them less flexible for accessibility.
  • Example:

p {
  font-size: 16px;
}

Ems (em):

  • The “em” unit is relative to the font size of the parent element. If no parent size is set, it’s relative to the browser’s default font size (usually 16px).
  • Ems can be useful for creating scalable and responsive designs.
  • Example:

p {
  font-size: 1.5em; /* 1.5 times the parent's font size */
}

Rems (rem):

  • Similar to “em,” but it’s relative to the root element’s font size (usually the <html> tag).
  • Using “rem” can make it easier to maintain consistent typography across the entire page.
  • Example:

p {
  font-size: 1.5rem; /* 1.5 times the root font size */
}

Viewport Width (vw):

  • “vw” units are relative to the width of the viewport, or the visible area of the browser window.
  • It’s often used for responsive typography to make font sizes adjust to the screen width.
  • Example:

h1 {
  font-size: 5vw; /* 5% of the viewport width */
}

Viewport Height (vh):

  • “vh” units are similar to “vw” but are relative to the viewport’s height instead of width.
  • This can be useful for creating font sizes that depend on the screen height.
  • Example:

h2 {
  font-size: 8vh; /* 8% of the viewport height */
}

Here’s a simple HTML and CSS example using these units:

Copy code
<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      font-size: 16px;
    }
    
    p {
      font-size: 1.5em;
    }

    h1 {
      font-size: 3rem;
    }

    h2 {
      font-size: 4vw;
    }

    h3 {
      font-size: 6vh;
    }
  </style>
</head>
<body>
  <h1>Heading 1 (3rem)</h1>
  <h2>Heading 2 (4vw)</h2>
  <h3>Heading 3 (6vh)</h3>
  <p>Paragraph (1.5em)</p>
</body>
</html>

In this example, font sizes for headings and paragraphs are set using various units. The actual font sizes will depend on the base font size of the <body> element and the viewport size.

Screenshot-2023-11-09-223701
Previous
How To Work CSS Backgrounds - background-color,
Next
CSS Position - static, relative, absolute, sticky, fixed