Skip to content

CSS Max-width

Controlling Element Width for Responsiveness

Section titled “Controlling Element Width for Responsiveness”

Recall that block-level elements (like <div>, <p>, <h1>) naturally expand to fill the full width of their parent container.

Setting the width property restricts an element to a specific size. Combining a fixed width with margin: auto; is a common way to center a block element horizontally.

Example with width:

.fixed-width-box {
width: 500px; /* Fixed width */
margin: 20px auto; /* Center horizontally (top/bottom 20px) */
border: 3px solid #8AC007;
padding: 10px;
}
This <div> element has a width of 500px and is centered.

If the browser window or screen becomes narrower than the element’s fixed width (e.g., 500px), the browser will introduce a horizontal scrollbar. This creates a poor user experience, especially on mobile devices.

The max-width property offers a more flexible solution. It sets the maximum width an element can have, but allows it to shrink narrower if the container is smaller.

An element with max-width will behave like this:

  • If the container is wider than the max-width value, the element will take up the max-width value (and can be centered using margin: auto).
  • If the container is narrower than the max-width value, the element will shrink to fit the container’s width (typically 100% of the container width).

Example with max-width:

.flexible-width-box {
max-width: 500px; /* Maximum width, can shrink */
margin: 20px auto; /* Center horizontally */
border: 3px solid #8AC007;
padding: 10px;
}
This <div> element has a max-width of 500px and is centered. Try resizing your browser window!

Prefer max-width over width for main layout containers or elements that need to adapt to different screen sizes. This simple change significantly improves responsiveness and prevents horizontal scrollbars on smaller devices.

Practical Application: Using max-width on the main content wrapper of a webpage is a fundamental technique for creating responsive layouts.