CSS max-width Property

CSS max-width property specifies the maximum width of an element’s content area. It basically sets an upper bound on the element’s width.

If the content of the element is larger than its max-width, the height of the element changes automatically to adjust the content. But, if the content is smaller than the max-width, the max-width property has no effect on the element. This makes the element more flexible. Refer to the example below:

Example:

div{
  max-width: 200px;
}

The max-width property overrides the width property. That is, if the value of the width property is greater than the max-width, the width property is restricted to use the value specified by the max-width property.

In the example below, the width property is restricted to use the value of max-width i.e. 200px. Try it out:

Example:

div{
  width: 1000px;
  max-width: 200px;
}

The max-width property by default sets the maximum width of the element’s content area only. This means that the max-width does not include the padding and border of the element.

It simply means that two elements having same max-width but different padding or border will be of different size.

In the example below, the two <div> elements have exactly the same max-width but their actual size(width) will be different as their padding is not the same. Try it out:

Example:

.div1{
  max-width: 200px;
  padding: 10px;
}
.div2{
  max-width: 200px;
  padding: 40px;
}

Note: To include padding and border in element’s max-width, use box-sizing: border-box;


CSS Syntax

The max-width property has the below syntax:

max-width: none|length|%|initial|inherit;

Property Values

The max-width property accepts the following values:

noneThis is the default value. It specify no maximum width.
lengthSpecifies the max-width in a valid CSS length format such as ‘px’, ’em’, ‘rem’, ‘cm’, etc.
%Specify the max-width in percentage(%). The percentage value is calculated from the total width of the parent container(element).
initialSets the max-width property to its default value(none).
inheritInherits the max-width from the parent element.

General Info

Default Valuenone
InheritedNo
JavaScript Usageelement.style.maxWidth = “200px”;