Units are used to describe different expressions like lengths or
colors (width
,height
, font-size
, ...).
There are two types of units:
The table below presents the 6 absolute units used to describe fixed lengths:
Unit | Description | Relation |
---|---|---|
px | pixel | 96 pixels = 1 inch |
mm | millimeter | 10 mm = 1cm |
cm | centimeter | 2.54 cm = 1 inch |
in | inch | 1 inch = 25.4mm = 96 pixels |
pt | point | 72 points = 1 inch = 96 pixels |
pc | picas | 1 pica = 12 points |
Important note: You must not put a space between the value and its
unit: 100 px
must be written 100px
.
Here is an example where the 6 declarations define identical widths in different units:
.pixel { width: 300px; }
.millimetre { width: 79.375mm; }
.centimetre { width: 7.9375cm; }
.inch { width: 3.125in; }
.point { width: 225pt; }
.pica { width: 18.75pc; }
The relative sizes make it possible to create responsive websites. These are websites whose pages automatically adapt to the medium on which they are displayed. For example, this site (Le blog de Lulu) is responsive: if you change the size of the window, you see that its layout automatically adapts to the new size.
The table below presents the relative units:
Unit | Description | Note |
---|---|---|
em | relative to the font size of the element | 2em = 2 times the font size |
rem | relative to the document's root tag (<html> ) |
2rem = 2 times the size of the main font |
% | percentage of parent element or max value | 100% = same as parent element |
vw | relative to the width of the window (V iewport W idth) | 100vw = the width of the window |
vh | relative to the height of the window (V iewport H eight) | 100vh = the height of the window |
vmin | relative to the smallest dimension of the window | 100vmin = min (height, width) of the window |
vmax | relative to the largest dimension of the window | 100vmax = max (height, width) of the window |
Here is an example to define the width of the elements that will adapt automatically to the window size:
.half-window { width: 50vw; }
.half-parent { width: 33%; }
Here is another example where the texts of the class twice
will be twice
the size of their parents:
.twice { font-size: 2em; }
Let's considere the following HTML code:
<div id="alert">This is an alert</div>
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
Add CSS styles to display the previous code according to the following preview: