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 of16px
. - The child
div
has a font size of12px
. - 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 of16px
. - The child
div
has a font size of0.75em
, which means it's 75% of the parent's font size (12px
).
Key Differences:
-
px
Example: Child font size is fixed at12px
, 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.