Categories
CSS max-width
is a property used to set the maximum width that an element can take up on a web page. It is particularly useful for ensuring that an element doesn't exceed a certain width, even if the available space or the content inside the element would otherwise allow it to expand further.
The max-width
property is often used with block-level elements like <div>
or images (<img>
), as well as with elements set to display: inline-block;
.
Syntax:
selector {
max-width: value;
}
Example:
Let's say we have a container <div>
and we want to limit its width to 500 pixels, but we still want it to adjust its width if the viewport is smaller than 500 pixels. Here's how we can use max-width
to achieve this:
<!DOCTYPE html>
<html>
<head>
<title>Max Width Example</title>
<style>
.container {
max-width: 500px;
background-color: lightblue;
padding: 20px;
}
</style>
</head>
<body>
<div class="container">
<h1>This is a Heading</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed maximus feugiat orci eget ultrices. Maecenas euismod arcu sed quam fermentum ultricies.</p>
</div>
</body>
</html>
In this example, the .container
div has a max-width
of 500 pixels. If the viewport is larger than 500 pixels, the div will take up the full available width. However, if the viewport is smaller than 500 pixels, the div will adjust its width accordingly and not exceed the specified maximum width.
Using max-width
is especially helpful for creating responsive designs that adapt to different screen sizes, ensuring that content remains readable and visually pleasing on various devices.
Note that max-width
sets an upper limit, while width
sets a fixed width for an element. If you want an element to have a fixed width regardless of the viewport size, you can use width
. However, if you want the element to adjust its width based on the viewport size, use max-width
.