CodeBlanks Logo Icon CodeBlanks

Pixel and percentage

CSS course · Beginner · Lesson 60/82

Learn px and % units.

What is a pixel?

In CSS, the pixel (px) is the best-known absolute unit. When you write 16px, the browser treats it as a fixed length; the px value does not change when the screen or the parent changes.

Pixels are handy for font sizes, border widths and small gaps. For example, font-size: 16px looks consistent across devices.

The percentage unit

The percentage (%) unit is computed against the container. If you write width: 50% for a .box, the box takes half of its parent's width.

As the parent's width changes, the percentage changes too; that is why it works well in flexible layouts. For height, it is computed against the parent's height.

Absolute vs relative

Units come in two kinds: absolute units stay fixed on the device (px, pt), relative units change with a context (%, em, vw).

Absolute units are consistent but rigid. Relative units make the design adapt to the screen, which is why they are preferred in responsive work.

Exercise Mix percentage and pixel for a box

Write a .box selector. Set its width to 80% and its padding to 16px.

Show example solution
/* add the .box selector */
.box {
  width: 80%;
  padding: 16px;
}

Test yourself

  1. Which one is an absolute unit?

    /* an absolute unit stays fixed on the device */
    • %
    • px
    • em
    • vw
    Show answer

    px — Correct. px is an absolute unit; it stays fixed even when the screen or the parent changes.

  2. Write the width as a percentage

    .box {
      width: ____%;
    }
    Show answer
    .box {
      width: 50%;
    }
  3. Match each unit to its kind

    px
    Absolute pixel unit
    pt
    Absolute point unit
    %
    Relative to parent
    em
    Relative to font size

All lessons in Beginner