What happens if I have both a background-color and background-image?


#1

Question

What happens if I have both a background-color and background-image property on the same element?

Answer

When we have both a background-color and background-image property applied to the same element, whichever property that is physically lower in the CSS file will be applied. In the example code our background-image property is physically lower in the CSS file and will be rendered to the page instead of the background-image property. If however, the background-image URL value fails to load, the background-color property will be applied instead.

Example:
HTML:

<!DOCTYPE html>
<html>
<head>
  <title>My Site</title>
</head>
<body>
  <div>
    <h1>Hello World</h1>
  </div>
</body>
</html>

CSS:

div {
  height: 200px;
  width: 200px;
  color: white;
  background-color: rebeccapurple;
  background-image: url('https://images.unsplash.com/photo-1535544320549-1d65b9d3d9d7');
  background-size: cover;
}