Skip to main content

CSS Max-width Property

The width property specifies the width of an element, while the max-width property specifies the maximum width that an element can have.

Here's an explanation of the difference between these two properties:

The width property

This property sets the width of an element to a specific value, such as width: 200px;.

If the content within the element is wider than the specified width, the content will overflow and may be hidden, depending on the overflow property.

The max-width property

This property sets the maximum width of an element to a specific value, such as max-width: 500px;.

If the content within the element is wider than the maximum width, the element's width will be limited to the maximum width, and the content will wrap to the next line. If the content is narrower than the maximum width, the element's width will adjust accordingly.

As an example:

Editor

Loading...

In this example:

  • The .container element has a fixed width of 800px, but it will adjust its width to the size of the viewport if the viewport is narrower than 800px.
  • The max-width: 100% ensures that the element will never be wider than its parent container.
  • Inside the container, there is a h1 and a p element. The h1 element has a font size of 36px, a line height of 1.2, and a bottom margin of 20px.
  • The p element has a font size of 18px and a line height of 1.5.
  • These styles will apply regardless of the size of the viewport, but because the .container element has a maximum width of 100%, the text will adjust its width to fit the size of the viewport.