5 CSS Units You Should Know

5 CSS Units You Should Know

Useful CSS Units.

Featured on daily.dev

Unit Options

When writing CSS there are a lot of options for the units you can use.Here are some main ones 🖐 you need to be aware of and when to use them.

PX

Pixels are the most popular and well known CSS unit🥳. They are static and don't scale therefore are best for any value that won't change with screen size like borders and fixed size elements.

.button {
    border-radius: 5px;
    border: 1px solid #dcdcdc
}

Percentage %

Percentage units are also popular and are a good choice for responsive design.However ,% units don't always work as expected when setting heights so best to use them for widths only.

.wrapper {
width: 100%;
padding: 0 3%
}

/* Combine % and px */
.article {
    max-width: 30%;
    padding: 10px;
}

VH & VW

Viewport height and viewport width units are great for areas that need to take up a specific portion of the screen.

.banner-fullwidth {
width: 100vh;
height: 100vh;
}
.banner-image {
width: 45vw;
}

EM & REM

Em and Rem units are calculated based on the font size. It's usually best to stick with Rem units because they are based on the root font size and are more predictable.

/* base font 16px*/

.title {
    font-size: 2rem; /* 32px */
    line-height: 1.4;
}
.sub-title {
    font-size: 1.5rem; /* 24px */
    line-height: 1.2;
}

CH

Character units are brilliant for setting widths on text blocks.You can limit how many characters wide you want an element to be and that will be different based on the font size of the text.

.blog-text{
    max-width: 90ch;
}

.header {
    width: 20ch;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

Others

cm  - centimeters
mm  - millimeters
in  - inches
pt  - points
pc  - picas

These are some other units that are technically acceptable in CSS,but they aren't web units so it's better to avoid them.However,they can be useful for prints specific styles.

There is no best unit! 🤗

Don't pick one unit and try to use only that throughout the project --- it won't work well.instead,evaluate each thing you are trying to style and pick the best unit for the job! This will create a much more versatile and professional design that works across devices.

Photo by Pankaj Patel from unsplash