CSS Max Width
Using width, max-width and margin: auto;
css max width: As referenced in the previous chapter; a block-level element consistently takes up the full width accessible (stretches up to the left and right as far as it can).
Setting the width of a block-level element will keep it from stretching out to the edges of its container. Then, at that point, you can set the margins to auto, to horizontally center the element inside its container. The element will take up the specified width, and the remaining space will be split equally between the two margins:
Note: The issue with the <div> above happens when the browser window is smaller than the width of the element. The browser then, at that point adds a horizontal scrollbar to the page.
Using max-width instead, in the present circumstance, will work on the browser’s handling of small windows. This is significant when making a site usable on small gadgets:
Tip: Resize the browser window to less than 500px wide, to see the difference between the two divs!
Example
<!DOCTYPE html> <html> <head> <style> div.ex1 { width: 500px; margin: auto; border: 3px solid #73AD21; } div.ex2 { max-width: 500px; margin: auto; border: 3px solid #73AD21; } </style> </head> <body> <h2>CSS Max-width</h2> <div class="ex1">This div element has width: 500px;</div> <br> <div class="ex2">This div element has max-width: 500px;</div> <p><strong>Tip:</strong> Drag the browser window to smaller than 500px wide, to see the difference between the two divs!</p> </body> </html>
CSS Max-width
Tip: Drag the browser window to smaller than 500px wide, to see the difference between the two divs!
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your projects with us.