CSS - Units

aigle-levant · August 7, 2024

There exist units other than pixels that we haven’t yet looked into…

CSS data-type

[Referring : [CSS Data Types Codeguage](https://www.codeguage.com/courses/css/data-types)]

Every property in CSS requires a certain set of values.

Example, background-color can handle only values as such rgb(), hex-codes, etc. while font-family will only accept font names as values.

These ‘certain values’ are called the property’s data-type. They’re enclosed in angular brackets [these < >].

We can write them as :

  • <color> -> Representing name of colours
  • <length> -> Various units of length
  • <angle> -> Degrees, radians, etc.

And so on.

Do not confuse with color! The former is a data-type; the latter is a property.

[Referring : [CSS - Data Types Tutorialspoint](https://www.tutorialspoint.com/css/css_data_types.htm)]

We formally represent a property using these data types [with their brackets, of course] to show the values allowed with it.

selector
{
    property : <data-type>;
}

Numerical data types

  • <integer> - Any whole number
  • <number> - Any decimal [or even non-decimal] number
  • <dimension> - <number> with an unit attached to it
  • <percentage> - Percentage, i.e. fraction of a value

Lengths data types

[Referring : CSS Units - Scaler]

There are two types of lengths found in CSS :

  • Relative : Values will change depending on some other length property; dimensions will adjust as per screen size
  • Absolute : Values are fixed regardless of other factors; dimensions won’t change even if the screen were resized

px is the most widely used absolute unit. The rest [cm, in, mm, etc.] are used in prints, but even there, pixel reigns supreme.

em’s value is dependent on the font-size of the element.

Let’s look at this snippet below :

.container
{
    font-size : 20px;
    background-color: green;
    width: 2em;
}

The value of 1 em will be 20px since the value of font-size here is 20px as well. Therefore, width of this element will be 40px.

Whereas rem depends on the font-size of the root element.

:root
{
font-size: 16px;
}
.container
{
    font-size : 20px;
    background-color: green;
    width: 2rem;
}

Now, the root element is a pseudo-class representing the <html> tag [hence its name]. We can also swap it for html selector.

It has the font-size property of 16px.

Therefore rem’s value is also 16px, making the width be equal to 32px.

vh is relative to the viewport’s height while vw is relative to the viewport’s width.