An Interest In:
Web News this Week
- April 3, 2024
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
CSS Units
Hello Fellow Codenewbies
There are many factors in CSS to be considered when we think about responsiveness.
One of them is CSS Units.
There are two types of units:
- Absolute
- Relative - to the size of font (em, rem, etc.) and viewport (vh, vw, etc.)
- Absolute Unit
Regardless of its parent's or screen size, absolute units are always be the same size.
px, cm, inch, etc. are within this category.
<body> <div class="absolute"></div> <div class="relative"></div></body>
.absolute { background-color: green; width: 640px; height: 100px;}.relative { background-color: red; width: 90%; height: 6em;}
Try to shrink and expand the window in this example and see the difference.
- Percentage
Percentage mainly use for widths and it is relative to the target element's parent.
<body> <header> <h1>Hello World</h1> </header></body>
header { width: 80%;}h1 { width: 50%;}
Width of header
is 80% of body
and h1
is 50% of header
.
- em
em
inherits size from its parent.
<div class="container"> <h1>Hello World</h1></div>
.container { font-size: 12px;}h1 { font-size: 2em;}
The font size of h1
is 2x of its parent (container
), which makes it 24px.
But there is one problem with em
.
Because it is relative to its parent, it can create a cascading effect.
<body> <div class="container"> <h1>Hello World</h1> <ul> <li>List 1</li> <li>List 2</li> <li>List 3</li> </ul> </div></body>
body { font-size: 18px;}h1 { font-size: 2em;}ul { font-size: 1.5em;}li { font-size: 1.5em; }
I provide the example in Codepen here.
In this example, all font size of li
are bigger than h1
.
This happens because the font size of li
is 1.5x bigger than ul
, while ul
is 1.5x bigger than body
, which makes li
font size 3x bigger than body
's font size.
While h1
font size is set as 2x bigger than body
.
So when it's about font-size
, we better avoid the using of em
and use rem
instead.
- rem
rem
stands for "root element" and it is always relative to the "root" of the document, which is html
element.
<body> <div class="container"> <h1>Hello World</h1> <ul> <li>List 1</li> <li>List 2</li> <li>List 3</li> </ul> </div></body>
html { font-size: 10px;}body { font-size: 18px;}h1 { font-size: 2rem;}ul { font-size: 1.5rem;}li { font-size: 1.5rem; }
You can see the code in action here.
Regardless that the body
has 18px of font size, all rem
are relative to html
as the root element.
Picking Which Unit To Use
It really depends on your personal preference and what you need, but here is a reference of approaches on when to use one:
font-size:
rem
margin and padding:
em
width:
em
orpercentage
Note:
This post is one of my TIL note based on my learning on Scrimba platform.
Original Link: https://dev.to/adiatiayu/css-units-m76
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To