How do you create a box filled with color in HTML/CSS?

To create a box filled with color in HTML/CSS, you can use HTML to create the structure and CSS to apply the color. This is commonly achieved using block elements like <div> with CSS styling properties.

Syntax

selector {
    width: value;
    height: value;
    background-color: color;
}

Method 1: Using HTML div Element

The most common approach is to use an HTML div element and style it with CSS properties

  • HTML div tag Creates the box structure
  • CSS width and height Set the box dimensions
  • CSS background-color Fills the box with color

Example

Here is a complete example creating a green colored box using a div element ?

<!DOCTYPE html>
<html>
<head>
    <title>Creating a Color-Filled Box</title>
    <style>
        .color-box {
            width: 150px;
            height: 100px;
            background-color: #04af2f;
            border: 2px solid #333;
            margin: 20px;
        }
    </style>
</head>
<body>
    <h3>Color-Filled Box Example</h3>
    <p>This is a green rectangular box created using HTML div and CSS styling.</p>
    <div class="color-box"></div>
</body>
</html>
A green rectangular box (150px × 100px) with a dark border appears on the page with some margin spacing.

Method 2: Using SVG Rectangle

You can also create colored boxes using SVG elements for more precise control ?

Example

Here is an example using SVG to create a colored rectangle ?

<!DOCTYPE html>
<html>
<head>
    <title>SVG Color-Filled Box</title>
</head>
<body>
    <h3>SVG Color-Filled Box</h3>
    <p>This box is created using SVG rectangle element with fill color.</p>
    <svg width="160" height="110">
        <rect x="5" y="5" width="150" height="100" fill="#04af2f" stroke="#333" stroke-width="2"/>
    </svg>
</body>
</html>
A green rectangular box created with SVG, identical in appearance to the CSS version but using vector graphics.

Key Properties

Property Purpose Example Values
width Sets box width 100px, 50%, 10em
height Sets box height 80px, 200px, 5rem
background-color Fills with color #ff0000, red, rgb(255,0,0)

Conclusion

Creating colored boxes in HTML/CSS is straightforward using div elements with CSS styling. The div method is preferred for most web layouts, while SVG offers more precision for graphics-based applications.

Updated on: 2026-03-15T17:46:38+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements