The width property defines the horizontal dimension of an element’s content area. This is one of the most critical properties for building website layouts.
Defining Width Values
Similar to height, width can be set using various units:
auto: The default. Block-level elements (like<div>) will automatically take up $100\text{%}$ of the available horizontal space.- Length (
px,rem): Sets a fixed width. - Percentage (
%): Sets the width relative to the parent container. This is the key to responsive design. - Viewport Width (
vw): Sets the width relative to the browser window width.
Example Code:
.parent-width{
width: 100%;
}
.width1 {
width: 250px; /* Fixed width 250px */
}
.width2 {
width: 50%; /* Takes up 50% of its parent's width */
}
Output
Maximum and Minimum Width
To prevent a layout from breaking on very small or very large screens, we use limits:
min-width: Ensures the element doesn’t get too narrow (e.g., keeping a button readable).max-width: Ensures the element doesn’t get too wide (e.g., keeping lines of text from becoming too long on big monitors).
The “Max-Width” Benefit: If you use width: 500px;, the element is not responsive—it will stay 500px even on a small phone, causing a horizontal scrollbar. If you use max-width: 500px; width: 100%;, the element will grow to 500px but shrink naturally on smaller screens.
Example Code
.parent-width{
width: 100%;
}
.child-width {
min-width : 100px;
max-width : 200px;
}
Output
The Box Model Interaction
Remember: By default, if you add padding or border to an element with a fixed width, the element becomes wider than the width you set.
Always use this to keep your widths accurate:
* {
box-sizing: border-box;
}