Difference between max-width and width as well as max-height and height

What is the difference between max-width and width as well as max-height and height?

Last updated:7/20/2021 1:08:22 AM

1 Answers

Ethan Karla
Ethan Karla

Max-Width

As we know that 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.

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.

Using max-width instead, in this situation, will improve the browser's handling of small windows. 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.

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:

<!DOCTYPE html>

<html>
<head>
    <style>
        div.ex1 {
            width: 600px;
            margin: auto;
            border: 1px solid red;
        }
        div.ex2 {
            max-width: 600px;
            margin: auto;
            border: 1px solid red;
        }
    </style>
</head>
<body>
    <h2>CSS Max-width</h2>
    <div class='ex1'>This div element has width: 600px;</div>
    <br>
    <div class='ex2'>This div element has max-width: 600px;</div>
    <p>
        <strong>Tip:</strong> Drag the browser window to smaller than 600px wide, to see the difference between
        the two divs!
    </p>
</body>
</html>

 

Max-Height

The max-height property defines the maximum height of an element.

If the content is larger than the maximum height, it will overflow. How the container will handle the overflowing content is defined by the overflow property.

If the content is smaller than the maximum height, the max-height property has no effect.

Note: This prevents the value of the height property from becoming larger than max-height. The value of the max-height property overrides the height property.

Answer