Pre-define CSS background image center center position and cover background size

rainerbrunotte picture rainerbrunotte · Mar 9, 2016 · Viewed 7.4k times · Source

I am struggling to shorten down my CSS code for background image position (center center) and background size (cover).

Whenever I use the following code, it works fine, obviously:

HTML:

<div class="banner-divider" id="banner-divider-welcome"></div>
<div class="banner-divider" id="banner-divider-second"></div>

CSS:

.banner-divider{
width: 100%;
height:600px;
}
#banner-divider-welcome{
background: url(/images/welcome.jpg) no-repeat center center; 
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#banner-divider-second{
background: url(/images/second.jpg) no-repeat center center; 
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

I would like to shorten/delete multiple CSS repetitions of the center center and cover properties (as I have multiple banner ID's but with repeating background settings), however the following code does not center center and cover the images correctly:

HTML:

<div class="banner-divider" id="banner-divider-welcome"></div>
<div class="banner-divider" id="banner-divider-second"></div>

CSS:

.banner-divider{
width: 100%;
height:600px;
background: #fff;
background-image: none;
background-repeat: no-repeat
background-position: center center; 
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#banner-divider-welcome{
background: url(/images/welcome.jpg); 
}
#banner-divider-second{
background: url(/images/second.jpg); 
}

What am I doing wrong?

Answer

Moob picture Moob · Mar 9, 2016

You're overwriting the entire background property. Set background-image instead.

.banner-divider{
    width: 100%;
    height:600px;
    background: #fff;
    background-image: none;
    background-repeat: no-repeat; /* <- missing semi-colon */
    background-position: center center; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
#banner-divider-welcome{
    background-image: url(/images/welcome.jpg); /* <- here */ 
}
#banner-divider-second{
    background-image: url(/images/second.jpg);  /* <- and here */
}

.banner-divider{
    width: 100%;
    height:600px;
    background: #fff;
    background-image: none;
    background-repeat: no-repeat;
    background-position: center center; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
#banner-divider-welcome{
    background-image: url(https://placeimg.com/100/100/any);
}
#banner-divider-second{
    background-image: url(https://placeimg.com/150/150/any);
}
<div class="banner-divider" id="banner-divider-welcome"></div>
<div class="banner-divider" id="banner-divider-second"></div>