π‘ For those working in front-end development, understanding these units makes all the difference in creating responsive layouts that adapt to any screen. Let's take a quick look at the main ones:
π px (Pixels)
The well-known "pixel" is a fixed, absolute unit, meaning it doesnβt change. Itβs great when you need an exact size and want the element to appear the same on any device. Example: font-size: 16px;
π em
Hereβs where things get interesting! The em unit is relative, meaning its value depends on the font size of the parent element. This makes em super useful for flexible layouts. Example: if the base size is 16px, then 2em would be 32px. Everything depends on the context! π
π rem (Root EM)
Similar to em, but instead of relying on the parent element, it uses the font size of the root element (the ). This helps maintain consistent sizes across the site. If has font-size: 16px, then 1rem will always be 16px.
π vh (Viewport Height)
This unit is based on the height of the screen (viewport). 1vh represents 1% of the visible screen height. Itβs great for defining elements that occupy a specific portion of the window's height, like a banner that covers the full screen (height: 100vh;).
π vw (Viewport Width)
Similar to vh, but based on screen width. 1vw equals 1% of the screen width, and itβs commonly used for elements that should take up the full window width (width: 100vw;).
Quick Summary:
px: For fixed and specific sizes.
em: When you want the element to be flexible and context-dependent.
rem: For consistent global sizes (like font sizes).
vh and vw: For elements that need to adjust to screen size, like full-screen layouts.
These units are the secret to building interfaces that adapt to various devices. π
Top comments (2)
Great article, Yanaiara!
I'd just wanted to add that a "pixel" in CSS does not represent an actual physical pixel on the screen. That's because different devices might have different pixel sizes.
For example, an element with a width of 16 physical pixels might look ok in one screen, and extremely tiny in another screen.
For that reason, a CSS pixel is a "logical pixel" which has a relatively constant size across different devices. Sometimes, a logical pixel is bigger than a physical pixel.
Thank you so much for your comment and the detailed explanation! It's such an important point that really complements the article. The distinction between physical and logical pixels is crucial, especially for ensuring responsive and accessible designs. I appreciate the insight and will definitely keep it in mind for future discussions. π