You can add a background color in HTML primarily using CSS (Cascading Style Sheets), either inline, internally within the <style>
tag, or externally via a linked stylesheet. While the HTML bgcolor
attribute was previously used, it's now deprecated and not recommended.
Methods to Add Background Color:
1. Inline CSS
You can apply background color directly within an HTML element using the style
attribute and the background-color
CSS property.
<body style="background-color:#6B6B6B;">
<p>This paragraph has a grey background.</p>
</body>
In this example, the background-color
of the <body>
element is set to #6B6B6B
(a shade of grey). You can replace #6B6B6B
with any valid color value, such as a hexadecimal code, a color name (e.g., red
, blue
, green
), or an RGB or RGBA value.
2. Internal CSS (Within the <style>
tag)
You can define CSS rules within the <head>
section of your HTML document using the <style>
tag.
<!DOCTYPE html>
<html>
<head>
<title>Background Color Example</title>
<style>
body {
background-color: lightblue;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This paragraph has a lightblue background.</p>
</body>
</html>
Here, the background-color
of the <body>
is set to lightblue
. This approach is useful for styling a single page.
3. External CSS (Linked Stylesheet)
The most organized and maintainable approach is to use an external CSS file.
-
Create a CSS file (e.g.,
styles.css
):body { background-color: lavender; }
-
Link the CSS file to your HTML document:
<!DOCTYPE html> <html> <head> <title>Background Color Example</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>This is a heading</h1> <p>This paragraph has a lavender background.</p> </body> </html>
This keeps your styles separate from your HTML content, making your code cleaner and easier to manage, especially for larger projects.
Alternatives to background-color
Note that you can also control the background using:
background-image
: For setting an image as the background.background
: a shorthand property for setting multiple background properties at once (color, image, position, size, etc.).
For example:
body {
background: url("image.jpg") no-repeat center center fixed;
background-color: #f0f0f0;
background-size: cover;
}
Summary: Modern web development practices recommend using CSS, particularly inline, internal, or external stylesheets with the background-color
property to set background colors in HTML. Avoid the deprecated bgcolor
attribute.