CSS Width
The width property in CSS is used to specify the width of an element. It plays a key role in determining the layout of elements on a webpage, especially when used in conjunction with other layout properties like padding, margin, and border.
Key Points on CSS Width:
- The
width
property defines the width of an element’s content box, not including padding, borders, or margins. - Values for
width
can be specified in various units such as pixels, percentages, and more. - If the
box-sizing
property is set toborder-box
, the width will include padding and border in the element's total width. - In most cases, width is set to
auto
by default, which makes the element’s width adjust according to its content. - Setting
width
can influence the layout and positioning of adjacent elements in flex or grid layouts.
Syntax for CSS Width:
Syntax Example
/* Width property syntax */
width: value;
/* Example */
width: 300px;
Examples of CSS Width:
The following examples demonstrate how to use the width
property in CSS:
Code Example: Fixed Width
img {
width: 300px;
}
Output
 }})
Code Example: Width in Percentage
img {
width: 50%;
}
Output

Code Example: Auto Width
div {
width: auto;
}
Output
This div has an auto width, adjusting according to its content.
Common Width Values:
- px: Specifies the width in pixels. Useful for precise control over element size.
- %: Defines the width as a percentage of the parent element's width. This is useful for responsive layouts.
- auto: The element's width will automatically adjust based on its content and other properties.
- vw: Sets the width as a percentage of the viewport width, allowing for responsive designs.
- em: Specifies width relative to the font size of the element (useful for scalable layouts).
- rem: Similar to
em
, but based on the root font size of the page.
When using the width
property, consider the context in which it is being applied. For example, in a responsive design, it's common to use percentage-based widths, while fixed widths may be more appropriate for elements like buttons or images in certain designs.