CSS width Property
CSS width property sets the width of HTML Element(s).
The syntax to specify a value for width property is
width: value;
The following table gives the possible values that could be given to width property.
Value | Description | Examples |
---|---|---|
auto | The browser calculates the width based on the content or parent constraints. Default Value. | width: auto; |
CSS Length | A valid length in CSS Length Units. | width: 50px; |
Percentage | Width in percent of the parent element. | width: 20%; |
initial | Sets width to default value. | width: initial; |
inherit | Inherits 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
<!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
<!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.