CSS Layout - width and max-width

Using width, max-width and margin: auto;

As mentioned in the previous chapter; a block-level element always takes up the full width available (stretches out to the left and right as far as it can).

Setting the width of a block-level element will prevent it from stretching out to the edges of its container. Then, you can set the margins to auto, to horizontally center the element within its container. The element will take up the specified width, and the remaining space will be split equally between the two margins:

This <div> element has a width of 500px, and margin set to auto.
Note: The problem with the
above occurs when the browser window is smaller than the width of the element. The browser then adds a horizontal scrollbar to the page.

Using max-width instead, in this situation, will improve the browser's handling of small windows. This is important when making a site usable on small devices:

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

Tip: Resize the browser window to less than 500px wide, to see the difference between the two divs! Here is an example of the two divs above:

Example

div.ex1 {
    width: 500px;
    margin: auto;
    border: 3px solid #73AD21;
}

div.ex2 {
    max-width: 500px;
    margin: auto;
    border: 3px solid #73AD21;
}

CSS max-width Property

Example

Set the maximum width of a <p> element to 150 pixels:
p.ex1 {
max-width: 150px;
}

Definition and Usage

The max-width property defines the maximum width of an element.

If the content is larger than the maximum width, it will automatically change the height of the element.

If the content is smaller than the maximum width, the max-width property has no effect.

Note: This prevents the value of the width property from becoming larger than max-width. The value of the max-width property overrides the width property.