Sizing in CSS

Most HTML elements have a default size, including a height and width. However, we can use CSS to change their size!

Two of the most common sizing properties in CSS are the width and height properties.

For example, the <img> element has a default width and height set to the original size of the image:

As you can tell, the rendered image of our favorite bot character is 200 pixels-wide and 200 pixels-tall by default. But this can be changed in CSS by selecting the image and setting our own width and height properties:

img {
 width: 250px;
 height: 400px;

This is what our image now looks like:

Codédex image with altered width and height.

Our image is now taller than it is wide!


Absolute vs. Relative Units

The kinds of measurements we can give to an element’s properties can be split into two groups: absolute units and relative units.

Absolute units are usually expressed as numbers, with or without a decimal. They are fixed and do not change in size according to the size of its direct parent element.

Pixels (px) are the most commonly used ones:

element {
  width: 10px;
  height: 10px;
}

Other options include points (pt) and centimeters (cm)

Note:

 Be mindful of setting the height of a given element with absolute units, as it may cause the content to overflow outside the boundaries of its parent element.

If we set an element’s property with relative units, it will change if the size of something else changes, like its parent element or the computer screen itself!

They are often expressed as percentages (e.g., 50%):

element {
  width: 50%;
}

But other frequently-used relative units include:

  • em measurements that are associated with the font size of either the parent element when applying font-size or the element itself when setting the width.
  • rem measurements that are associated with the font size of the root <html> element (16pt, by default).

Uses for the em may include setting a page’s text to change according to how a user sets the text size for their browser. For rem, this could be used to set the baseline text size for their site.