Length units in HTML and CSS

How to use the different units of measurement in HTML and CSS.

1637 views
d

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:

  1. An in-dept look at the use of headings (h1-h6) and sections in HTML pages.
  2. Pagination can be a confusing thing to get right both practically and programmatically. I have put a lot of thought into this subject, and here I am giving you a few of the ideas I have been working with.
  3. The best way to deal with a trailing question mark is probably just to make it a bad request, because it is a very odd thing to find in a request URL.
  4. How to optimize image-loading and automatically include width and height attributes on img elements with PHP.
  5. HTTP headers are not case-sensitive, so we are free to convert them to all-lowercase in our applications.

More in: Web development