CSS width Property Tutorial

In this section, we will learn what the width property is and how to use it in CSS.

Click here to run the example of width property.

CSS width Property Definition and Usage

The CSS `width` property is used to fix a width for an HTML element.

Note: when we say width of an element, that means the size of its content without the size of its padding, borders, and margins.

These values are then can be added to the value of the width property to get the total width of an element.

CSS width property

If we want the value of the width property to be combined with the values of `padding` and `border` as well, we need to change the setting of CSS `box-sizing` property.

Note: using min-width and max-width will override the value of the width property.

CSS width Property Syntax

width: auto|value|initial|inherit;

CSS width Property Value

The value we set for this property is a number with any relative or absolute units supported in CSS.

For example, if we set the value 10vw for this property, that means the width is 10 percent of the viewport’s width.

If you used % value for this property, be aware that the percentage is based on the width of the parent of the target element.

That means if we set the value of the width property for an element to 40% for example, then this element takes 40% width of its parent element.

Note: the two global values “initial” and “inherit” can also be used as the value of this property.

Example: width in CSS

See the Pen width in CSS by Omid Dehghan (@enjoytutorials1) on CodePen.

How Does CSS width Property Work?

By default, the width of an HTML element is big enough to take the available space of its parent! For example, if the width of the parent is 100px, then the width of the target element becomes 100px as well (Including the size of padding, border, and margin).

But with the help of the width property, we can fix the size of the content of an element to any value we need.

Note: the width of a child element can also be set in a way that surpasses the width of its parent.

CSS width auto

The width property also takes a value called “auto”. This value is basically telling browsers that they should automatically calculate the width of the target element and decide how big it should be.

Note: this is the default value.

Example: width auto CSS

See the Pen width auto CSS by Omid Dehghan (@enjoytutorials1) on CodePen.

Note: Usually when the value of a width property is set to auto, the target element will take the entire width of its parent element.

Example: HTML div width

See the Pen HTML div width by Omid Dehghan (@enjoytutorials1) on CodePen.

Leave a Reply