One of the most common CSS questions I get is what’s the difference between background and background-color in CSS? The reason it’s confusing is that you often see developers using
background interchangeably when they apply background color to an element.
But they’re not the same. The
background (without -color) property can be used to set all the background properties for an element in one declaration. For example, you might want to add both a background color, an image that is displayed once (no-repeat), and an image position to an element in one single declaration, like this:
background: #444 url("image.jpg) no-repeat left top;
The above could also be written as such:
background-image: url(“url/image.jpg”); background-repeat: no-repeat; background-position-x: left; background-position-y: top; background-color: #444;
background property can be used as a convenient short-hand that can apply multiple declarations in one line, and save you many lines of code.
Declaration = CSS property + value.
background-color property, on the other hand, can only set the background color of an element. It’s like a subset (a part) of the bigger
If you’ve previously applied various background declarations on an element, e.g.
background-image, and then later on add a
background: red declaration to the same element, all your previous declarations will be reset, and now your element’s background is red, and your background image is gone.
Take a look at this Pen example, where we have three
div elements with the same
.box class. The first element only has the
.box class but the others also have a utility (helper) class of
Notice a difference?
The second box is all red, there’s no image, even though its
.box class clearly specifies that it should have the same JS image as the two other elements.
<div class="box"> </div> <div class="box bg-red"> </div> <div class="box bg-blue"> </div>
Take a close look at the CSS, and compare the
.bg-blue properties. The red class uses the ‘master’ (all-in-one)
backgroundproperty to set the red color value, whereas the blue class uses the single-purpose
background property on the
.bg-red class simply removes every other background declaration on the second div element: here
-color and then adds the specified
red value as the single background attribute for that element.
So, if you only want to affect the background colors of specific elements, make sure you use
background or you will overwrite any previous background- declarations on that element.
Sometimes, resetting all previous declarations may be exactly what you want to do. You could be working on a website that has a bunch of legacy code that you’re not allowed to touch (or want to haha) but you want to manipulate a specific element that already has a bunch of declarations that you need to replace with a new singular declaration value, e.g. color — for that, using
background is an excellent tool.