css – What's the difference between using background for background-color?

Question:

I have this code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <style>
      div {
        width: 400px;
        height: 400px;
        background: url("imagem/img1.jpg");
      }
    </style>
</head>
<body>
  <div></div>
</body>
</html>

The top code doesn't matter if I put background and background-image that works what's the difference?

Answer:

In this case, the background-image property could only have a single value.

background-image: url("imagem/img1.jpg");

What if in case you wanted to put background-repeat: no-repeat for the image not to repeat? easy add property.

background-image: url("imagem/img1.jpg");
background-repeat: no-repeat;

And for the image to stay fixed and change position? obviously add the properties.

background-image: url("imagem/img1.jpg");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 50% 50%;

What if my image has a transparent background and I wanted to add a background color? it's the last time! add the property.

background-color: rgb(140, 50, 190);
background-image: url("imagem/img1.jpg");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 50% 50%;

Did you notice anything in the last snippet of code? here, if you wanted to change the color, image, not repeat, fix and the position, you would have to define 5 properties and that makes your CSS code very large and for that you have the background property, which is a shorthand property, that is, a property abbreviated with it you define the 5 properties that I mentioned in the code above in just a single property.

background: rgb(140, 50, 190) url("imagem/img1.jpg") no-repeat fixed 50% 50%;

It seems a little complicated but no, just follow this order regardless if one of the values ​​is missing.

background-color
background-image
background-repeat
background-attachment
background-position

As you go deeper into CSS you will see that there are other shorthand properties (shorthand) and I bet you've already made use of some of them.

margin
padding
border
border-radius
animation
transition
Scroll to Top