In this chapter, we will learn about the CSS properties width and max-width and how they are used to control the layout of elements on a web page. These properties are essential for creating flexible and responsive designs.
Width
The width property sets the width of an element. It can be specified using various units such as pixels (px), percentages (%), ems (em), and more. The width property defines the horizontal space that an element will occupy.
Syntax
element {
width: value;
}
Example
div {
width: 200px;
}
HTML
<div>This div has a width of 200 pixels.</div>
Width with Percentages
Using percentages for the width property allows the element to take up a percentage of its containing element’s width.
Example
div {
width: 50%;
background-color: lightblue;
}
HTML
<div>This div takes up 50% of the container's width.</div>
Max-Width
The max-width property sets the maximum width of an element. It prevents the element from growing wider than the specified value, regardless of its content or container size. The max-width property is useful for creating responsive designs.
Syntax
element {
max-width: value;
}
Example
img {
max-width: 100%;
}
HTML
<img src="image.jpg" alt="Responsive image">
In this example, the image will resize to fit within its container while maintaining its aspect ratio, but it will not exceed 100% of the container’s width.
Combining Width and Max-Width
You can use both width and max-width properties together to create flexible layouts that adapt to different screen sizes.
Example
.container {
width: 80%;
max-width: 1200px;
margin: 0 auto;
}
HTML
<div class="container">
<p>This container is 80% of the viewport width but will not exceed 1200 pixels.</p>
</div>
Examples of Using Width and Max-Width
Example 1: Fixed Width
.box {
width: 300px;
background-color: lightcoral;
padding: 10px;
}
HTML
<div class="box">This box has a fixed width of 300 pixels.</div>
Example 2: Percentage Width
.container {
width: 90%;
background-color: lightgreen;
padding: 10px;
margin: 0 auto;
}
HTML
<div class="container">
<p>This container takes up 90% of the viewport width and is centered.</p>
</div>
Example 3: Responsive Image
.responsive-img {
max-width: 100%;
height: auto;
}
HTML
<img src="image.jpg" class="responsive-img" alt="Responsive image">
Example 4: Combining Width and Max-Width
.wrapper {
width: 80%;
max-width: 1000px;
background-color: lightblue;
margin: 0 auto;
padding: 20px;
}
HTML
<div class="wrapper">
<p>This wrapper takes up 80% of the viewport width but will not exceed 1000 pixels. It is also centered.</p>
</div>
Conclusion
In this chapter, you learned about the CSS width and max-width properties, including how to set fixed and percentage widths and how to use max-width for responsive designs. Understanding these properties is essential for creating flexible and adaptive layouts that work well on different screen sizes and devices.