width
The width of an element.
Syntax
width: value;Values
| Parameter | Type | Description |
|---|---|---|
| px | length | A fixed width: `300px`. |
| % | percentage | A percentage of the parent's width. |
| auto | keyword | Blocks take the full available width (the default). |
| fit-content | keyword | As wide as the content, but no wider than the parent. |
Examples
Fixed, percentage and automatic width:
<style>
div { background: lightskyblue; padding: 6px; margin-bottom: 6px; }
</style>
<div style="width: 200px;">200px</div>
<div style="width: 50%;">50% of the parent</div>
<div>auto — the full width</div>Width by content:
<div style="width: fit-content; background: gold; padding: 6px;">As wide as the text</div>Notes
By default width sets the width of the content only, and padding and border are added on top — box-sizing: border-box changes that. Inline elements like <span> ignore width. For responsive layouts prefer max-width to a fixed width.
See also
- height — The height of an element.
- max-width — The maximum width: the element can be narrower, but never wider.
- min-width — The minimum width: the element cannot become narrower.
- box-sizing — Whether `width` and `height` include the padding and the border.
Related recipes
In the tutorial
- The box model — What an element consists of in CSS — content, padding, border and margin, sizes, centering and box-sizing.