max-width

The max-width property in CSS sets the maximum width of an element. This means that the element will not exceed the specified width, even if the content within it tries to expand beyond that point. This is particularly useful for creating responsive designs.

Syntax

max-width: value;

Values

You can use various units for the max-width property:

  • Length units: px, em, rem, cm, in, etc.
    • Example: max-width: 800px;
  • Percentages:
    • Example: max-width: 80%; (relative to the parent element’s width)

Example

<div class="container">
  <div class="content">
    This is some content that might get really long.
  </div>
</div>
.container {
  width: 90%;
  margin: 0 auto;
}

.content {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background-color: lightgray;
}

In this example:

  • The .container div fills 90% of the available width and is centered horizontally.
  • The .content div has a maximum width of 600 pixels. If the content within it exceeds 600 pixels, it will wrap to the next line instead of expanding the container. The content is also centered within the container.

Key Points

  • max-width doesn’t prevent the element from being smaller than the specified value. It only sets an upper limit.
  • You can combine max-width with width and min-width for more complex layout control.
  • max-width is crucial for responsive design to ensure elements adapt to different screen sizes.

Common Use Cases

  • Creating responsive layouts
  • Limiting the width of images and other elements
  • Preventing text from overflowing

By understanding and effectively using max-width, you can create more flexible and adaptable web designs.