CSS - Width and max-width Layout

    max-width and width are two block-level properties of an element. Generally, if we do not mention this to a block-element, then it will stretch up to full width, and take all the space from left to right according to its block.

    CSS - Width and max-width Layout

    But by setting the width property, we can manipulate the width of an element and prevent its automatic stretching and occupying full with of its container. When we reduce or fixed the width of an element, then it is recommended to set the padding property to auto, because it makes a good interface and the element will be rendered in the specified width automatic padding.

    Example

    <p style="border: 2px solid black; width: 50%; padding: auto; "> 
        This paragraph is widht of 50% and auto padding
     </p>
    <p style="border: 2px solid black; width: 50%; margin: auto; "> 
        This paragraph is widht of 50% and auto margin
    </p>

    Preview

    This paragraph has a width of 50% and auto padding

    This paragraph has a width of 50% and auto margin

    max-width

    In many cases the browser window happens to be smaller than the specified width then the browser adds a horizontal bar to the page so the user can see the content which is out of the browser display. To solve this problem we generally use the % and auto values, but if we have used px, and cm values then setting max-width is a good option. The max-width, handle the static width of the element and make it dynamic according to the display size. The max-width property set a maximum width for the element, and if the browser display width is smaller than the max-width property value than the browser resizes the width of the element according to the browser display size.

    Example

    <p style="border: 2px solid black; width: 500px; margin: auto; "> 
        This paragraph has a widht of 500px and auto margin
    </p>
    <p style="border: 2px solid black; max-width: 500px; margin: auto; "> 
        This paragraph has a max-widht of 500px and auto margin
    </p>
    <p>To See the Difference reduce the size of your browser window</p>

    Preview

    This paragraph has a widht of 500px and auto margin

    This paragraph has a widht of 500px and auto margin

    To See the Difference reduce the size of your browser window

    Summary

    • width is generally used to manipulate the width of a block-level element.
    • By default, the block level elements took the full width of the container.
    • The max-width set the maximum value for the element width.
    • If the browser size is less than the max-width, then the browser resize the element width according to the browse display size.