Controlling Maximum Width in CSS with `max-width`: Building Responsive Layouts

Learn how to use the CSS `max-width` property to control the maximum width of HTML elements. This tutorial explains its functionality, demonstrates its use with different units (px, em, %, etc.), and shows how to prevent elements from becoming too wide on smaller screens, creating responsive and well-structured web designs.



Setting Maximum Width with CSS `max-width`

Understanding `max-width`

The CSS `max-width` property sets the maximum width of an element's content box (the area inside padding). An element's width can be smaller than the `max-width` value, but it cannot be larger. This is crucial for creating responsive designs and preventing elements from becoming excessively wide, particularly on smaller screens. This property only affects the width; the height of the element may adjust automatically if the content exceeds the `max-width`.

`max-width` Property Values

  • none (default): No maximum width restriction.
  • (e.g., `300px`, `10em`, `5cm`): Specifies the maximum width using length units.
  • initial: Resets the property to its default value (none).
  • inherit: Inherits the `max-width` value from its parent element.

Negative values are not allowed for `max-width`.

`max-width` Property Syntax

The syntax is:

max-width: none | | initial | inherit;

Example: Setting Maximum Widths for Paragraphs

This example demonstrates setting different maximum widths for several paragraphs using various length units. The text content is the same for each paragraph. If the content is wider than the `max-width`, the paragraph's width will be constrained to the `max-width`, and its height will adjust accordingly to fit the text within the defined maximum width.

CSS Code

p {
  max-width: 175px; /* First paragraph */
}

p:nth-child(2) { /* Second paragraph */
  max-width: 20em;
}

p:nth-child(3) { /* Third paragraph */
  max-width: 350pt;
}

p:nth-child(4) { /* Fourth paragraph */
  max-width: 10cm;
}

Observe the differences in the paragraph's width and how the height adjusts as needed based on the content and the `max-width` settings.