width

Definition

The width CSS property sets the width of an element’s content area. It controls the horizontal size of an element and is fundamental for creating layouts, responsive designs, and controlling element dimensions. The width property affects the content area by default, but can be modified with the box-sizing property to include padding and borders.

Syntax

.component {
  width: 40rem;
}

Set width with absolute units, responsive percentages, or viewport-based lengths depending on the layout needs.

Values

  • <length>: fixed sizes using px, rem, em, vh, vw, and other length units.
  • <percentage>: resolves against the size of the containing block (for width) or the available height when explicitly defined.

Practical Examples

.content {
  width: min(90vw, 70ch);
  max-width: 960px;
}

This pattern keeps copy readable on large screens while still shrinking gracefully on smaller devices.

HTML

With width: 40rem

This panel uses width: 40rem, so it stops expanding past that width.

Without width

The panel stretches to fill the grid column.
Code
<div class="grid gap-4 sm:grid-cols-2">
  <div class="space-y-3 rounded-lg border border-slate-200 bg-white p-4 shadow-sm">
    <p class="text-xs font-semibold uppercase tracking-wide text-slate-500">With width: 40rem</p>
    <div class="rounded-md border border-dashed border-slate-300 bg-slate-50 p-4 text-sm text-slate-700" style="width: 40rem; width: 100%;">
      This panel uses width: 40rem, so it stops expanding past that width.
    </div>
  </div>
  <div class="space-y-3 rounded-lg border border-slate-200 bg-white p-4 shadow-sm">
    <p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Without width</p>
    <div class="rounded-md border border-dashed border-slate-300 bg-slate-50 p-4 text-sm text-slate-700">
      The panel stretches to fill the grid column.
    </div>
  </div>
</div>

Tips & Best Practices

  • Use min()/max()/clamp() to express responsive bounds without relying on many media queries.
  • Combine width constraints with margin: 0 auto; to center fixed-width blocks.
  • Avoid hard-coded pixel values for layout-critical components; lean on fluid units that adapt to user zoom levels.

Accessibility & UX Notes

Ensure interactive controls remain at least 44px in their tap target size when you constrain dimensions. Strategic max widths also improve readability for long-form copy by keeping line lengths manageable.

Browser Support

Fully supported across modern desktop and mobile browsers. When supporting legacy IE, avoid logical properties such as inline-size unless you supply explicit fallbacks.

  • min-width, max-width, min-height, max-height for complementary constraints.
  • box-sizing to control whether padding and border are included in the computed size.
  • Logical properties (inline-size, block-size) for writing-mode aware layouts.