The max-width
property in CSS is used to set the maximum width of an element.
This property is useful for ensuring that an element doesn't exceed a certain width, even if the content inside it would normally require more space.
Syntax:
element { max-width: value; }
value: This can be a length (like px
, em
, rem
), a percentage (%
), or the keyword none
(which is the default and means no maximum width is applied).
Example:
Let's say you have a container that you want to expand to the full width of the screen but not exceed 600px, even if the screen is wider than that.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .container { width: 100%; max-width: 600px; background-color: lightblue; margin: 0 auto; padding: 20px; text-align: center; } </style> <title>Max-Width Example</title> </head> <body> <div class="container"> This container has a max-width of 600px. </div> </body> </html>
Explanation:
.container { width: 100%; }
: This sets the width of the container to 100% of its parent element (or the viewport if it's the root element)..container { max-width: 600px; }
: This ensures that the container will never be wider than 600px, even on large screens..container { margin: 0 auto; }
: This centers the container horizontally on the page when it doesn't occupy the full width..container { padding: 20px; }
: This adds space inside the container around the content.