width

Term side of the Card.
Topic: Sizes & Margins
Unit title: width
Categories: Property
Explanation side of the Card

Explanation: The property that defines the width of an element. It can be set using specific values, such as pixels, percentages or other units, controlling how much horizontal space the element occupies within its container.

Browser compatibility:
  • The chrome browser supports this feature starting from version 1.
  • The edge browser supports this feature starting from version 12.
  • The firefox browser supports this feature starting from version 1.
  • The safari browser supports this feature starting from version 1.
Availability: 

Example

Wrongcss
.container {
  width: 1200px;
  margin-inline: auto;
}
Rightcss
.container {
  width: min(100% - 2rem, 1200px);
  margin-inline: auto;
}

min() caps the width at '1200px' but shrinks it on small screens, keeping a side gutter.

Common mistakes

  • A fixed width in pixels overflows on small screens.
  • width: 100% plus padding makes the element wider than its parent.

Key points

  • Layout containers use max-width or min() instead of a fixed pixel width.
  • Elements with width: 100% and padding use box-sizing: border-box.
  • Full-width sections use '100%', not '100vw', to avoid horizontal scrolling.

Interview questions

What is the default width of a block element?

'auto', which fills the containing block's width minus margins, border and padding.

What is the difference between width: auto and width: 100%?

'auto' fits the available space including margins, while '100%' sets the content box to the parent width and can overflow with padding or margins.

Does width work on inline elements?

No. width is ignored on non-replaced inline elements like span; use 'inline-block' or another display value.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy