Length units in HTML and CSS
How to use the different units of measurement in HTML and CSS.
By. Jacob
Edited: 2019-09-30 02:04
In HTML and CSS, length units help us control the dimensions and position of elements. Traditionally, the pixel unit has been very popular, as it gives precise control over the dimensions of elements. More recently Em has started to replace pixels, as it allows for more flexibility.
Pixels (px) | One unit of px equals one dot on the screen. Since browsers implemented "page zoom" it is not nearly as bad to use pixels as it was in the past. |
Ems (em) | 1em equals 16px, depending on the parent elements font-size. We suggest setting a default font-size on the body element to better control what 1em corresponds with. |
Exes (ex) | One "ex" equals the size of "X", (similar to em's "M"). |
Percentages (%) | Ideal for flexible and fluid layouts, it's often a good idea to declare a minimum and max-width in pixels. |
Inches (in) | Best suited for Print-Media Types. |
Centimeter (cm) | Best suited for Print-Media Types. |
Millimeter | Best suited for Print-Media Types. |
Pixels are ideal in situations that demands pixel-precision. Usually when you are working with a lot of raster graphics, or image backgrounds. This is not as bad as some designers want to make it, but you may still want to consider using CSS media queries to design for a variety of screen resolutions.
To create a layout that automatically fits the screen resolution, a combination of percentages and EMs will often be the best choice.
Using the length units
body {
/* Sets the font-size for all text */
font-size: 0.8em;
}
div {
/* Sets the min/max width of a division */
width: 100%;
min-width: 900px;
max-width: 1600px;
}
Note. The above are just examples, you would most likely need additional code, depending on the layout you are trying to make.
Tell us what you think: