CSS Max-Width


Using width, max-width and margin: auto; A block-level element always occupies the entire available width, as was indicated in the preceding chapter.

A block-level element's width setting will stop it from encroaching on the edges of its container. The element can then be horizontally centered within its container by setting the margins to auto. The element will fill the allotted width, with the leftover space being divided equally between the two margins:

This <div> element has a width of 400px, and margin set to auto.

Note: The <div> above has a problem when the browser window is not wide enough to accommodate it. After that, the browser extends the page with a horizontal scrollbar.

In this case, max-width should be used in order to optimize the browser's handling of small windows. Making a website compatible with mobile devices requires the following:

This <div> element has a max-width of 400px, and margin set to auto.

Tip: To view the difference between the two div, resize the browser window to less than 400px wide.

Example

Preview