max-width of 100px vs width of 100px , why max-width is shorter than width?

I want to understand the difference of those two thank you

max-width:100px

width:100px

body{
      max-width: 1080px;
      width: 1080px;
      background-color: floralwhite;
      margin:0px;
      padding: 0px;
    }

p{
      width:100px; /* and max-width of 100px; */
      padding: 20px;
      margin:0px;
      float:left;
    }

The max-width attribute only uses the entire width if needed, depending on the content or padding. The width attribute will always use the specified amount (in your case 100px).

See my example here.

You can read more about it on MDN:

max-widthThe max-width CSS property is used to set the maximum width of an element. It prevents the used value of the width property from becoming larger than the value specified by max-width.

widthThe width property specifies the width of an element. By default, the property defines the width of the content area. If box-sizing is set to border-box, it instead determines the width of the border area.

The max-width property is used to set the maximum width of an element.

This prevents the value of the width property from becoming larger than max-width.

Note: The value of the max-width property overrides width.

So if both are specified in the styles then if the width property is less than the max-width then the width property will be applied, else the max-width property will be applied instead.

I think if you specify the max-width only then the width property will default to ‘auto’ , but will still be restricted to the max-width specified.

You can think of the width property as being more strict than the max-width property.

  • Width says: “You should be this width and nothing else.”
  • Max-width says: “Be whatever width you want, just not bigger than this width.”

You can see this with the demo you provided. The natural width of the boxes is around 50px, not bigger than 100px so max-width doesn’t really care. However, width sees that the boxes aren’t 100px and so sets them to be 100px.