CSS Max-Width
The CSS max-width
property sets the maximum width of an element. It prevents the element from becoming wider than a specified value, regardless of its content or the width of its container.
Understanding the Max-Width Property
The max-width
property is useful for creating responsive designs and ensuring that elements do not exceed a certain width, which helps maintain readability and layout consistency.
Syntax
The syntax for the CSS max-width
property is:
/* Max-Width Property Syntax */
selector {
max-width: ;
}
- Value: Specifies the maximum width. This can be set in units such as pixels (
px
), percentages (%
), viewport width (vw
), etc.
Examples
Example 1: Max-Width in Pixels
/* Max-Width in Pixels */
.max-width-px {
max-width: 400px;
background-color: #e0e0e0;
padding: 20px;
}
This element has a maximum width of 400px. Resize the window to see the effect.
Example 2: Max-Width in Percentages
/* Max-Width in Percentages */
.max-width-percent {
max-width: 80%;
background-color: #c1c1c1;
padding: 20px;
}
This element has a maximum width of 80% of its parent container's width. Resize the window to see the effect.
Example 3: Max-Width with Responsive Images
/* Max-Width for Responsive Images */
img {
max-width: 100%;
height: auto;
}
This image will resize responsively with a maximum width of 100% of its container.
Example 4: Max-Width with Viewport Units
/* Max-Width with Viewport Units */
.max-width-vw {
max-width: 50vw;
background-color: #9e9e9e;
padding: 20px;
}
This element has a maximum width of 50vw (50% of the viewport width). Resize the window to see the effect.