In CSS, the max-width
property is used to set the maximum width of an element. This property is particularly useful for ensuring that an element does not exceed a specified width, especially when the viewport or parent container is narrower.
Here's the basic syntax for using max-width
:
cssselector { max-width: value; }
px
), ems (em
), percentages (%), or other valid CSS length units.For example, if you want to set the maximum width of an element with the ID "example" to 500 pixels, you would use the following CSS:
css#example {
max-width: 500px;
}
This ensures that the element will not exceed a width of 500 pixels, regardless of the actual content width.
Here's a quick example with an HTML snippet:
html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.container {
max-width: 800px;
margin: 0 auto; /* Center the container horizontally */
padding: 20px;
background-color: #f0f0f0;
}
</style>
<title>Max-width Example</title>
</head>
<body>
<div class="container">
<!-- Your content goes here -->
<p>This is an example with a maximum width of 800 pixels.</p>
</div>
</body>
</html>
In this example, the .container
class has a max-width
of 800 pixels, ensuring that it won't expand beyond that width, and it's centered in the viewport using margin: 0 auto;
. Adjust the values based on your specific requirements.