The max-width
property in CSS is used to set the maximum width of an element. This property ensures that the element’s width does not exceed the specified value, even if the content inside the element requires more space. It is particularly useful for creating responsive designs, ensuring that elements do not become too wide on larger screens.
Syntax
selector {
max-width: value;
}
values of max-width
1. none
(default) The element has no maximum width.
2. length
Specifies a fixed maximum width using units such as px
, em
, rem
, etc.
.container {
max-width: 700px;
}
3. percentage
Specifies a maximum width as a percentage of the containing element’s width.
.container {
max-width: 80%;
}
4. inherit
The element inherits the max-width
value from its parent.
.container {
max-width: inherit;
}
5. initial
Sets the property to its default value.
.container {
max-width: initial;
}
6. unset
Resets the property to its natural value.
.container {
max-width: unset;
}
Important Points
The max-width
property can override the width
property if the specified width
exceeds the max-width
value.
Combining max-width
with other properties like min-width
, width
, and max-height
can create highly controlled and flexible layouts.