CSS width property

The CSS width property is used to set the width of an element. It defines how wide an element should be, and can accept various types of values including lengths, percentages, or keywords.

Syntax

selector {
    width: value;
}

Possible Values

Value Description
auto Browser calculates the width automatically (default)
length Defines width in px, em, rem, cm, etc.
% Defines width as a percentage of the parent element
initial Sets width to its default value
inherit Inherits width from the parent element

Example: Setting Fixed Width

The following example demonstrates setting a fixed width of 200 pixels for a paragraph −

<!DOCTYPE html>
<html>
<head>
<style>
    .fixed-width {
        width: 200px;
        height: 50px;
        border: 2px solid green;
        padding: 15px;
        margin: 20px;
        background-color: #f0f8ff;
    }
</style>
</head>
<body>
    <p class="fixed-width">
        This paragraph is 200 pixels wide and 50 pixels high
    </p>
</body>
</html>
A light blue paragraph with green border appears, exactly 200 pixels wide with the specified text content.

Example: Percentage Width

This example shows how to set width as a percentage of the parent container −

<!DOCTYPE html>
<html>
<head>
<style>
    .container {
        width: 400px;
        border: 1px solid #ccc;
        padding: 10px;
    }
    
    .percentage-width {
        width: 75%;
        background-color: #ffeb3b;
        padding: 10px;
        border: 1px solid #333;
    }
</style>
</head>
<body>
    <div class="container">
        <div class="percentage-width">
            This div is 75% width of its parent container
        </div>
    </div>
</body>
</html>
A yellow div element that takes up 75% of its parent container's width (300px of 400px) with a dark border.

Conclusion

The width property is fundamental for controlling element dimensions. Use fixed values for precise control or percentages for responsive layouts that adapt to their containers.

Updated on: 2026-03-15T11:21:52+05:30

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements