Difference Between em and px Units with examples

Differences between em and px units with some examples using HTML and CSS

Example 1: Using px for Font Size

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Using px for Font Size</title>
<style>
.parent {
font-size: 16px; /* Parent element font size set to 16 pixels */
}
.child {
font-size: 12px; /* Child element font size set to 12 pixels */
}
</style>
</head>
<body>
<div class="parent">
Parent Text
<div class="child">
Child Text
</div>
</div>
</body>
</html>

In this example:

  • The parent div has a font size of 16px.
  • The child div has a font size of 12px.
  • Both sizes are explicitly defined in pixels (px)

Example 2: Using em for Font Size

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Using em for Font Size</title>
<style>
.parent {
font-size: 16px; /* Parent element font size set to 16 pixels */
}
.child {
font-size: 0.75em; /* Child element font size set to 0.75em (75% of parent's font size) */
}
</style>
</head>
<body>
<div class="parent">
Parent Text
<div class="child">
Child Text
</div>
</div>
</body>
</html>

In this example:

  • The parent div has a font size of 16px.
  • The child div has a font size of 0.75em, which means it's 75% of the parent's font size (12px).

Key Differences:

  • px Example: Child font size is fixed at 12px, regardless of the parent's font size.
  • em Example: Child font size is relative to the parent's font size, maintaining proportionality. If you change the parent's font size, the child's font size will adjust accordingly.

Ad


Related aticles

Leave a comment

Your email address will not be published. Required fields are marked *

Please note, comments must be approved before they are published