Units in CSS: first thing to remember is that a whitespace doesn't exist between digit/s and unit, for example, 10 px is incorrect, 5 em is incorrect; but 10x is correct and 5em is correct.
- Relative units: em (relative to parent), rem (relative to root html), % (relative to browser font-size).
- Fixed units: px
- Other units of the world: In Eric A. Meyer's The Definite Guide, they are mentioned as, in, cm, mm, pt, and pc.
My favourites are em, rem, % and px; so let's talk about them. People choose different units for different reasons. I think these four units are good to start with.
Proving: em is relative to a parent (not to the root html, only; though root can be a parent). Check below example in your browser.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
html {font-size: 6px;}
body {font-size: 2em;} /*2em=2*6px=12px*/
div {font-size: 2em;} /*2em=2*12px=24px*/
</style>
</head>
<body> <!--child of html=2*6px=12px-->
<div>
line 1 <!--child of body=2*12px=24px-->
<div> <!--child of div=2*24px=48px-->
line 2
<div><!--child of div=2*48px=96px-->
line 3
</div>
</div>
</div>
</body>
</html>
Proving: rem is relative to the root html (not to the parent). Check the below, yes in your browser.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
html {font-size: 6px;}
body {font-size: 2rem;} /*2rem=2*6px=12px*/
div {font-size: 12rem;} /*12rem=12*6px=72px*/
</style>
</head>
<body> <!--child of html=2*6px=12px-->
line 0
<div> <!--12rem=12*6px=72px-->
line 1
<div> <!--12rem=12*6px=72px-->
line 2
<div> <!--12rem=12*6px=72px-->
line 3
</div>
</div>
</div>
</body>
</html>
Percentage
% is relative to browser's font-size, if browser's font-size is 16px, then 100% is equal to 16px. Different browsers have different font-size, and along with them your 100% will vary.
Pixel
px is fixed unit, like % it's not set by browser's font-size, it's what you set.
Below example is for % and px, there is nothing like parent-child with them.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
.fifty {font-size: 100%;}
.hundred {font-size: 200%;}
/* px */
.sixteen {font-size: 16px;}
.thirty-two {font-size: 32px;}
</style>
</head>
<body>
<!--for % -->
<div class="fifty">
fifty
<div class="hundred">
hundred
</div>
</div>
<span class="hundred"> hundred again </span>
<!-- for px -->
<div class="sixteen">
sixteen
<div class="thirty-two">
thirty-two
</div>
</div><span class="thirty-two"> thirty-two again </span>
</body>
</html>
Final words
Generally I've seen people using mix of em, rem, % and px -- where one of them doesn't work well, other works.
Comments
Post a Comment