CSS Maximum Width
CSS max-width
is a property that sets the maximum width of an element. This means the element's width will not exceed the value defined by max-width
, but it can be smaller if the content or its container is narrower. It is commonly used to ensure that elements don’t become too wide on larger screens or containers.
Here’s a basic example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Max Width Example</title>
<style>
.container {
max-width: 800px; /* Maximum width is 800px */
margin: 0 auto; /* Center the container */
padding: 20px;
background-color: lightgray;
}
.content {
background-color: white;
padding: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
<p>This container has a maximum width of 800px. If the viewport is wider than 800px, the container will stay at 800px. If the viewport is narrower, the container will shrink accordingly.</p>
</div>
</div>
</body>
</html>
Explanation:
.container
: This element has amax-width
of800px
. It will not exceed 800px in width, but if the viewport is smaller than 800px, it will shrink to fit the smaller space.- Centering:
margin: 0 auto;
centers the.container
horizontally within its parent element (in this case, the body).
Responsive Design Example:
You can use max-width
to create a responsive design:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Max Width Example</title>
<style>
.responsive-box {
max-width: 100%; /* Box will never exceed 100% of its parent container */
width: 500px; /* Default width of the box */
padding: 20px;
background-color: lightblue;
box-sizing: border-box; /* Includes padding in the element's width */
}
</style>
</head>
<body>
<div class="responsive-box">
<p>This box has a maximum width of 100% of its parent container, but its default width is 500px. On smaller screens, it will adapt to fit the container width.</p>
</div>
</body>
</html>
Explanation:
.responsive-box
: Has a default width of500px
but will scale down to fit within its parent container if the viewport is smaller.max-width: 100%
: Ensures that the box never exceeds the width of its parent container.
Tips:
- Use
max-width
with percentage values to make elements adapt to different screen sizes while maintaining a maximum size. - Combine with
min-width
to ensure elements don’t get too narrow, e.g.,min-width: 200px; max-width: 100%;
.
Feel free to ask if you have any specific scenarios or additional questions about max-width
!
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.