CSS propertyBox model

width

Sets the width of an element.

Initial value
auto
Inherited
No
Animatable
yes, as a length or percentage
Applies to
all elements except non-replaced inline elements (e.g. `<span>`), table rows, and row groups
JavaScript
element.style.width = "240px"
On this page

Example

#
CSS
.card {
  width: 100%;
  max-width: 320px;
}
Preview

Definition and usage

#

The width property sets the width of an element’s content area. With the default box-sizing: content-box, padding and border get added on top of that value, which is why many projects set box-sizing: border-box globally.

Block-level elements with width: auto stretch to fill all the available width of their parent. Percentages are calculated against the width of the containing block, and the min-content, max-content, and fit-content keywords size the element to fit its content.

On inline elements such as <span> or <a>, width has no effect. You need to change their display to inline-block or block, or use them inside a flex or grid container.

Syntax

#
Syntax
width: auto | <length> | <percentage> | min-content | max-content | fit-content;

Values

#
  • auto

    A block-level element fills all the available width of its parent.
  • 160px

    <length>

    A fixed width in pixels or another length unit.
  • 50%

    <percentage>

    Half the width of the containing block.
  • max-content

    The width of the longest line of content, with no wrapping.
  • fit-content

    As much as the content needs, but no more than the available space.

Values in practice

#

auto

A block-level element fills all the available width of its parent.
.demo { width: auto; }

160px

A fixed width in pixels or another length unit.
.demo { width: 160px; }

50%

Half the width of the containing block.
.demo { width: 50%; }

max-content

The width of the longest line of content, with no wrapping.
.demo { width: max-content; }

fit-content

As much as the content needs, but no more than the available space.
.demo { width: fit-content; }

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • A max-width is often a better choice than a fixed pixel width. The element can then narrow on small screens.
  • Set *, *::before, *::after { box-sizing: border-box; } in your stylesheet so width includes the padding and border too.

Related entries

#

Spotted a mistake or missing an example? Write to us.