Computer >> Computer tutorials >  >> Programming >> Programming

How to change background color in HTML/CSS

To add a background color to an HTML element, you can use the CSS property background-color.

Let’s say you have the following HTML markup, and you want to add a background color to the <body> element:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Changing background color in HTML/CSS</title>
</head>
<body>    
    <h1>Here's an awesome website!</h1>
</body>
</html>

The simplest way to add the background color is to create an internal <style> element in your HTML document.

In the <head> element in the HTML, create a set of <style></style>tags. Then you can add the CSS style rules for the background color in the <style> element.

<head>
    <meta charset="UTF-8">
    <title>Changing background color in HTML/CSS</title>    
    <style>
        body {
            background-color: #78a8eb;
        }
    </style>
</head>

This HTML and CSS code will result in a webpage that looks like this!

How to change background color in HTML/CSS

Color notation

The #78a8eb value for the background-color property is written in hexadecimal notation, also called hex. It represents the color with a set of characters each for Red, Green, and Blue channels. The characters range from numbers 0 to 9, then letters A-F. Zero (0) is the lowest value, and F is the highest value.

You can also represent colors in CSS using other notations.

For example, in functional notation, the color is formatted as rgba(). In our example the background color would be written like this:

background-color: rgb(120, 168, 235);

Or in HSL (Hue, Saturation, Lightness) notation it would be written like this:

background-color: hsl(215, 74%, 70%);

Any of these three ways of writing colors is acceptable in modern browsers.

Deprecated methods (don’t use)

In previous versions of web standards, people would use the bgcolorproperty with a hex color in the HTML tag itself:

<body bgcolor="#78a8eb" ></body>

However, this is an old way of setting background colors. You shouldn’t use this anymore– just stick to writing CSS styles to control colors.