The max-width property in CSS is essential for controlling how wide an element can grow. It allows you to set an upper limit on the width of an element, which can be particularly useful for responsive design and ensuring that elements do not become too wide on larger screens.
The max-width property sets the maximum width of an element's content box. This means the element can be narrower than the specified maximum width, but it will not exceed that width.
If the content of an element exceeds the max-width value, the element's width will be limited to the max-width, and the content may cause the element's height to adjust accordingly.
If the content is smaller than the max-width, the element's width will naturally adjust to fit the content without any impact from the max-width property.
max-width: none | length | initial | inherit;
• Description: This is the default value. It means there is no limit to the width of the content box, so the element can grow as wide as its container allows.
• Syntex: max-width: none;
• Description: Specifies the maximum width of the element in units like pixels (px), centimeters (cm), points (pt), etc.
• Syntex: max-width: 500px; (limits the width to 500 pixels)
• Description:Resets the property to its default value (none). It effectively removes any previously set maximum width.
• Syntex: max-width: initial;
• Description: Inherits the max-width value from its parent element. Useful for maintaining consistent styling in nested elements.
• Syntex: max-width: inherit;
<!DOCTYPE html>
<html>
<head>
<title>CSS Max Width Example</title>
<style>
.box-1 {
border: 1px solid black;
padding: 10px;
max-width: 300px;
width: 100%;
margin-bottom: 20px; <!-- Added margin for spacing between
boxes -->
}
.box-2 {
border: 1px solid black;
padding: 10px;
max-width: 50%;
width: 100%;
}
</style>
</head>
<body>
<div class="box-1">
This box will have a maximum width of 300px. If the container is smaller,
the box will adapt to fit within it, but it will not exceed 300px in width.
</div>
<div class="box-2">
This box will have a maximum width of 50% of its container's width. It will
resize accordingly but will not be wider than 50% of its container's width.
</div>
</body>
</html>