DEV Community

Yanaiara Oliveira
Yanaiara Oliveira

Posted on

πŸ’‘ Do you know the different units of measurement in CSS? px, em, rem, vh, and vw! πŸ’‘

πŸ’‘ 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. 🌐

CSS #Frontend #WebDev #ResponsiveDesign #DevTips #CSSUnits #WebDevelopment

Top comments (1)

Collapse
 
whereisthebug profile image
@whereisthebug

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.