CSS Layout - width and max-width
- Previous Page CSS Display
- Next Page CSS Positioning
Using width, max-width, and margin: auto;
As described in the previous chapter, block-level elements always occupy the full available width (as much as possible to the left and right).
Set the width of a block-level element width
This will prevent it from extending to the edge of its container. Then, you can set the margin to auto to center the element horizontally within its container. The element will occupy the specified width, and the remaining space will be evenly distributed between the two margins:
Note:When the browser window is smaller than the element's width, the above <div>
will cause problems. The browser will add a horizontal scrollbar to the page.
In this case, using max-width
This can improve the browser's handling of small windows. This is important to make the website usable on small devices:
Tip:Please adjust the size of the browser window to less than 500 pixels 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; {}
- Previous Page CSS Display
- Next Page CSS Positioning