As discussed earlier, a block-level element naturally occupies the entire available width, extending to the edges on both sides.
However, setting a specific width for a block-level element confines it within that width, preventing it from extending to the container’s edges. By setting the margins to auto, you can horizontally center the element within its container. In this scenario, the element will occupy the designated width, and the surplus space will be evenly distributed between the two margins.
NOTE: When the browser window is narrower than the width of the element, the issue with the <div> mentioned above arises, resulting in the addition of a horizontal scrollbar to the page.
However, employing max-width instead in such circumstances enhances the browser’s management of smaller windows. This is particularly crucial for ensuring the usability of a website on smaller devices.
Tip: Adjust the width of the browser window to less than 500px to observe the contrast between the two divs!
Below is an illustration of the aforementioned pair of divs:
Example
div.ex1 { width: 500px; margin: auto; border: 3px solid #73AD21; } div.ex2 { max-width: 500px; margin: auto; border: 3px solid #73AD21; } |