width
Sets the width of an element.
- Initial value
auto- Inherited
- No
- Animatable
- yes, as a length or percentage
- Applies to
- all elements except non-replaced inline elements (e.g. `<span>`), table rows, and row groups
- JavaScript
element.style.width = "240px"
Example
#.card {
width: 100%;
max-width: 320px;
}<div class="card stage">
<strong>Python course</strong>
<p style="margin: 6px 0 0">The card is at most 320px wide, and it narrows on small screens.</p>
</div>Definition and usage
#The width property sets the width of an element’s content area. With the default box-sizing: content-box, padding and border get added on top of that value, which is why many projects set box-sizing: border-box globally.
Block-level elements with width: auto stretch to fill all the available width of their parent. Percentages are calculated against the width of the containing block, and the min-content, max-content, and fit-content keywords size the element to fit its content.
On inline elements such as <span> or <a>, width has no effect. You need to change their display to inline-block or block, or use them inside a flex or grid container.
Syntax
#width: auto | <length> | <percentage> | min-content | max-content | fit-content;Values
#- A block-level element fills all the available width of its parent.
<length>
A fixed width in pixels or another length unit.<percentage>
Half the width of the containing block.- The width of the longest line of content, with no wrapping.
- As much as the content needs, but no more than the available space.
Values in practice
#auto
.demo { width: auto; }160px
.demo { width: 160px; }50%
.demo { width: 50%; }max-content
.demo { width: max-content; }fit-content
.demo { width: fit-content; }Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- A
max-widthis often a better choice than a fixed pixel width. The element can then narrow on small screens. - Set
*, *::before, *::after { box-sizing: border-box; }in your stylesheet sowidthincludes the padding and border too.
Related entries
#- heightSets the height of an element.
- max-widthSets a maximum width the element won’t grow beyond.
- min-widthSets a minimum width the element won’t shrink below.
- box-sizingDecides whether width and height include the padding and border.
- aspect-ratioSets the ratio of an element’s width to its height.
- inline-sizeSets the element’s size along the text line. In horizontal writing that’s the width, and its pair block-size sets the height.
Spotted a mistake or missing an example? Write to us.