This site is mobile accessible. Press the "Tap Here" button to use a smaller font-size.

Smartphone icons created by Freepik - Flaticon

6.2 CSS Max-width

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. Check it out on your smartphone, tablet and laptop/desktop. This site will display almost the same across all devices. N.B. This element extends beyond the the white background of the content area when using Firefox mobile on Android phones.

Note: The problem with the <div> above occurs when the browser window is smaller than the width of the element. The browser then adds a horizontal scrollbar to the page. On Android phones running Firefox for mobile, the <div> element extends beyond the edge of the phone's screen. No scroll bars appear, however the rest of the element block may be seen by swiping left in the browser window.

Using max-width instead, in this situation, will improve the browser's handling of small windows (or small displays like smartphones). 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. Check it out on your smartphone, tablet and laptop/desktop. This site will display almost the same across all devices. N.B. This element DOES NOT extends beyond the the white background of the content area when using Firefox mobile on Android phones.

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: CSS Max-width
div.ex1 {
  width: 500px;
  margin: auto;
  border: 3px solid #73AD21;
}

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