Juneikerc.com

How to set a background color in HTML with CSS

Featured image of the post: How to set a background color in HTML with CSS

The CSS property responsible for this is background-color, followed by the color code. You can set the value directly in your HTML or in your CSS stylesheet.

For example, to change the background of an HTML button, you can apply the following CSS code.

html
<button>button text</button>
css
button {
background-color: #00ddaa;
/* Remember that HTML buttons come with a default border that often looks not very good; you can remove it with the following line */
border: none;
}

Although this example is functional, you have different examples to change the background color of your HTML content. On the other hand, if you're interested in setting a background image in HTML, check out this article.

Changing the HTML background color of the entire web

Generally, if we need the background color to apply throughout the site, we should set the background-color property on the body of our HTML. For example, to set the background color of the body to black, you can use the following code:

css
body {
background-color: #21222c;
/* This color is not entirely black, but for a dark background on a website,
it's better to use a color like this rather than pure black as it's too intense.
*/
}

How to change the background color in HTML for div and p tags

For this example, we will add a black background to a div tag and a white background to a p tag with black text color.

css
div {
background-color: hsl(240, 1%, 20%);
color: #efefef;
}
p {
background-color: hsl(240, 1%, 100%);
color: #000000;
}

The rules are the same for any tag; always remember to establish an accessible contrast between the element's background and text color.

Adding background color using inline CSS

Although it's not recommended to use inline styles to add CSS to HTML, there may be times when we need to use them. To set the background color of an HTML element with inline styles, you can use the following code:

html
<body style="background-color: rgba(41,41,41,0.5); color: #efefef;">
<p>This is a body with a black background and white text.</p>
</body>
<div style="background-color: rgba(41,41,41,0.5); color: #efefef;">
This is a div with a black background.
</div>
Juneiker Castillo freelance web developer

I am Juneiker Castillo, a passionate front-end web developer deeply in love with programming and creating fast, scalable, and modern websites—a JavaScript enthusiast and a React.js lover ⚛️.

About me