loading

CSS Max-width

Using width, max-width and margin: auto;

A block-level element, as was said in the previous chapter, always occupies the entire width that is available and extends as far to the left and right as it can.

A block-level element can be made to stop extending to the boundaries of its container by setting its width. After that, you can center the element within its container horizontally by setting the margins to auto. The element will occupy the designated width, with the two edges sharing the remaining space equally:

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

Note: When the browser window is smaller than the element’s width, the <div> above becomes problematic. The page then has a horizontal scrollbar added by the browser.

In this case, using max-width will help the browser handle small windows better. When designing a website to be readable on small devices, this is crucial:

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

Tips: Resize the browser window to a width of no more than 500 pixels to observe the distinction between the two divs!

The two divs above are shown in this example:

Example

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

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

CSS Max-width

Or copy link

Explore Topic