📏 CSS width
— Control the Width of Elements
The width
property specifies the width of an element’s content area. It’s one of the most fundamental properties for controlling layout and sizing in CSS.
🔹 What Does width
Do?
- Sets the horizontal size of block-level elements, replaced elements (images, videos), and some inline-block elements.
- Works alongside padding, border, and margin to determine total element size.
- Helps create responsive, fixed, or fluid layouts.
📘 Syntax
selector {
width: auto | <length> | <percentage> | max-content | min-content | fit-content;
}
✅ Common Values Explained
Value | Description |
---|---|
auto | Default. Width determined by content or parent. |
<length> | Fixed width (e.g., 100px , 50em , 10rem ). |
<percentage> | Width relative to the parent element’s width (e.g., 50% ). |
max-content | Width fits the largest content without wrapping. |
min-content | Width fits the smallest content without overflow. |
fit-content | Width fits content but limits to a maximum size. |
✍️ Examples
1. Fixed Width
.box {
width: 300px;
background-color: lightblue;
}
✅ The .box
element is always 300 pixels wide.
2. Percentage Width
.container {
width: 80%;
background-color: lightgreen;
}
✅ The .container
takes 80% of its parent’s width, resizing responsively.
3. Using max-content
and min-content
.text {
width: max-content;
background-color: lightcoral;
}
✅ The .text
box expands to fit its longest line without wrapping.
🖼️ Image Idea: Width Behavior
Visualize boxes with different widths inside containers:
- Fixed width box (300px)
- Percentage width box (50%)
- max-content vs min-content boxes
- Auto width adapting to content
💡 Tips for Using width
- Remember the box-sizing model affects total width (
content-box
vsborder-box
). - Use percentages for fluid layouts that adapt to screen sizes.
- Combine with max-width and min-width for flexible control.
- Avoid fixed widths on small screens for responsive design.
✅ Summary
Property | width |
---|---|
Purpose | Set the horizontal size of elements |
Default value | auto (size depends on content/parent) |
Units | Length units (px , em , rem ), percentage, keywords |
Use cases | Layout design, responsive sizing, element fitting |
🔚 Final Thought
The width
property is key to shaping your webpage’s layout — whether fixed, fluid, or content-based. Master it to build clean, responsive designs.