Skip to content
Tutorials Center
My learning

Topics

CSS Reference ยท Units and Values

The px unit

Reference for the CSS px unit: what a CSS pixel really is, how it relates to device pixels and zoom, when to use it, and when relative units are better.

px is the most common CSS length unit. One px is a CSS pixel, which is defined as 1/96 of an inch on paper and, on screens, as the size of a "reference pixel": roughly what one pixel looks like on a typical desktop monitor viewed at arm's length. It is not necessarily one dot of your screen.

On a high-density display, one CSS pixel is drawn with several device pixels. A phone with a device pixel ratio of 3 uses a 3 by 3 block of device pixels for each CSS pixel, so 1px borders stay crisp and layouts keep the same proportions across devices.

CSS
.card {
  width: 320px;
  border: 1px solid #cbd5e1;
  border-radius: 8px;
}

Try it

Pixel sizes and the device pixel ratio

Zoom the page in your browser and the bars grow while the numbers stay the same: browser zoom changes how many device pixels make one CSS pixel.

Syntax

CSS
<length> = <number>px
  • Applies to: any property that accepts a <length>.
  • Fixed relations: 1in = 96px, 1cm is about 37.8px, 1pt is 1.333px.
  • Fractions: allowed, for example 0.5px or 10.5px; the browser snaps or anti-aliases as needed.
  • Animatable: yes, as part of a length.

Values

Value Description
<number>px A length of that many CSS pixels. 0px may be written as plain 0.
Negative values Valid for properties that allow them, such as margin or top.

Usage notes

  • Good for details. Borders, outlines, small shadows, hairlines and icon sizes are natural places for px.
  • Be careful with text. A font size set in px is not changed when the user raises the default font size in their browser settings. Use rem or em for text and spacing that should scale with that preference.
  • Zoom still works. Browser zoom scales px values, so px layouts are not "unzoomable"; the problem is only the separate font-size preference.
  • Not a physical size. A 100px box is not a fixed number of millimeters. Use absolute units only for print.
  • Thin borders. On high-density displays a 1px border can look thicker than the hardware allows; some designs use 0.5px, which browsers render differently.
  • Media queries. px breakpoints work, but em breakpoints respect user font size.

Browser support

Supported in every browser.

  • rem โ€“ relative to the root font size
  • em โ€“ relative to the element's font size
  • Absolute units โ€“ cm, mm, in, pt, pc, Q
  • % โ€“ relative to a reference value
  • Lesson: CSS Units