CSS Max-width
max-width caps how wide an element is allowed to grow. Paired with width: 100%, it's the simplest responsive container pattern in CSS.
Why max-width beats fixed width
max-width is a ceiling. On smaller screens the element just shrinks.The responsive container recipe
CSS
.container {
width: 100%;
max-width: 1100px;
margin-left: auto;
margin-right: auto;
padding-left: 20px;
padding-right: 20px;
}
Tip: Use the same pattern for media:
img, video { max-width: 100%; height: auto; } stops anything overflowing its parent.Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS Max-width</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Make this image responsive while keeping its aspect ratio.
img { max-width: 100%; height:
; }
Let the browser pick the height.
Discussion
Loading…