As a coding newbie, my first encounter with CSS units was not very pleasant. There are enough of them to confuse someone who has just started their coding journey. So, if you are using rem
all the time because you are clueless about what em
,vh
,vw
and others are, here's an explainer for you.
CSS units can be divided into two types - Absolute Units and Relative Units
Absolute units: These are straight forward units with fixed size. One centimetre is one centimetre irrespective of the size of the screen. Hence, these are suitable for environment where output screen size is fixed and known. Given below are the absolute units we can use in CSS-
px
: One device pixel of the displaymm
: One millimetrecm
: One centimetrein
: One inchpt
: One point (which is 1/72 of an inch).pc
: One pica (which is 12 points).
Relative Units: As the name suggests, these are relative to something, say, font-size. This ensures the scalability of the webpage across screen-sizes. Given below are the relative units in CSS-
-
rem
andem
: These units are relative to the font sizes.rem
corresponds to the font-size of root element andem
corresponds to the font size of parent element.
div {
font-size: 10px;
}
div h2 {
font-size: 3em;
}
Here font-size
of h2 will be 30px
body {
font-size: 10px;
}
div h2 {
font-size: 2rem;
}
Here font-size
of h2 will be 20px
-
vh
andvw
: While making a design responsive, percentage isn't the best solution all the time and this is wherevh
andvw
come to our rescue.vh
equals 1/100 of the height of the viewport (visible area of a web page). So, if the viewport height is 500px, 1vh equals 5px. Thus, unlike percentage,vh
vw
allow sizing based on viewport size.
div {
height: 100vh;
}
This will fill the entire height of the viewport.
Similarly, vw
corresponds to width of the viewport i.e. if the viewport width is 700px, 1vw equals 7px.
vmin
andvmax
: These units correspond to minimum and maximum values ofvh
andvw
.
Eg. Let's say, the viewport has a height of 900px and width of 500px. Here,vmin
will be 5px andvmax
will be 9px. Thus,vmin
is related to minimum of viewport's height and width andvmax
is related to maximum of viewport's height and width.ex
andch
: To understand these units, think of rem/em and addfont-family
to the relation. These units consider thefont-family
as they rely on dimensions of different fonts.ch
corresponds to width of character 0 in the particular font.ex
is defined by height of lower case x in the given font, which for many fonts is equal to 0.5em.
As we can see, the absolute units (cm
, mm
, in
, pt
and pc
) will have fixed size irrespective of the output environment. Since screen sizes vary too much, these units are not recommended. For this reason, the relative units are best suited for the web developers.
Top comments (0)