Encodera

Thanks for reading!

Donate to the site — we work hard for you.

HTML & CSS reference

max-width

The maximum width: the element can be narrower, but never wider.

Syntax

max-width: value;

Values

ParameterTypeDescription
pxlengthA limit in pixels.
%percentageA percentage of the parent; `100%` keeps an element within its parent.
chlengthThe width of the "0" character; `65ch` is a comfortable line length for text.

Examples

A content column centered on the page:

<style>
  .page { max-width: 300px; margin: 0 auto; background: whitesmoke; padding: 8px; }
</style>
 
<div class="page">On a wide screen this block is 300px wide and centered; on a narrow one it shrinks with the window.</div>

A picture never wider than its container:

<img src="/media/photo-800x500.jpg" alt="" style="max-width: 100%; height: auto;">

Notes

max-width is better than width for layout: on narrow screens the element shrinks instead of causing a horizontal scrollbar. max-width: 100% for images is part of almost every reset.

See also

  • width — The width of an element.
  • min-width — The minimum width: the element cannot become narrower.
  • @media — Applies rules only under given conditions — the window width, the system theme and others.
  • margin — The outer spacing of an element — the distance to its neighbors.

Related recipes

In the tutorial

  • The box model — What an element consists of in CSS — content, padding, border and margin, sizes, centering and box-sizing.

Thanks for reading!

Donate to the site — we work hard for you.