Generally, there is a lot of confusion in the selection or usage of units in CSS. But, they are things that affect the styling. So, they are the ones which should be handled with utmost care.
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 and won't change with screen sizes like borders and fixed-size elements.
.button{
border-radius: 4px;
border: 2px solid;
}
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, it's recommended to use them for widths only.
.wrapper{
width: 100%;
padding: 0 2%;
}
We can use a combination of % and px also
.article{
max-width: 30%;
padding: 20px;
}
VH and VW
Viewport height and viewport width units are great for areas that need to take up a specific portion of the screen.
.full_screen{
width: 100vh;
height: 100vh;
}
.image{
width: 45vw;
}
EM and 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.
Generally, the base font size is 16px. Therefore, 1rem = 16px
.heading{
font_size: 2rem; /* 32px */
line-height: 1.4;
}
.subheading{
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.
.article_text{
max_width: 70ch;
}
.headline{
width: 15ch;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
Others
Centimetres(cm), Millimetres(mm), Inches(in), Points(pt), Picas(pc). 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 print 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.
That's a wrap. Hope you enjoyed this. Connect with me on Twitter where I post some useful content.