CSS width Property

CSS width property sets the width of HTML Element(s).

The syntax to specify a value for width property is

</>
Copy
width: value;

The following table gives the possible values that could be given to width property.

ValueDescriptionExamples
autoThe browser calculates the width based on the content or parent constraints.
Default Value.
width: auto;
CSS LengthA valid length in CSS Length Units.width: 50px;
PercentageWidth in percent of the parent element.width: 20%;
initialSets width to default value.width: initial;
inheritInherits width value from its parent element.width: inherit;

Note: The width does not include padding, border, or margin.

Examples

In the following examples, we set width for the HTML Element(s), using width property, with different possible values.

width in px

In the following example, we set the width of paragraph, with 100px, using width property.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        #p1 {
            border: 1px solid #DDD;
            width: 200px;
        }
    </style>
</head>
<body>
    <p id="p1">This is a paragraph with 200px width.</p>
</body>
</html>

width in Percentage

In the following example, we set the width of paragraph with 20%. Since, the parent of this paragraph is div, 20% of the div’s width is set as paragraph’s width.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        #div1 {
            border: 1px solid blue;
            width: 400px;
        }
        #p1 {
            border: 1px solid red;
            width: 20%;
        }
    </style>
</head>
<body>
    <div id="div1">
        <p id="p1">This is a paragraph with 20% width.</p>
    </div>
</body>
</html>

Conclusion

In this CSS Tutorial, we learned about width property, and how to use this property for HTML Elements, with examples.