预定义CSS背景图像中心位置和封面背景大小

时间:2016-03-09 10:24:34

标签: css css3 background-image background-position background-size

我正在努力缩短背景图片位置(中心位置)和背景尺寸(封面)的CSS代码。

每当我使用下面的代码时,它的工作正常,显然:

HTML:

$moderator

CSS:

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

我想缩短/删除中心的多个CSS重复并覆盖属性(因为我有多个横幅ID但具有重复的背景设置),但是下面的代码不会居中并正确覆盖图像:

HTML:

.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;
}

CSS:

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

我做错了什么?

2 个答案:

答案 0 :(得分:7)

您正在覆盖整个background媒体资源。改为设置background-image

.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>

答案 1 :(得分:1)

您需要使用background-image而不是使用background属性。

.banner-divider{
width: 100%;
height:600px;
background: #fff;
background-image: none;
background-repeat: no-repeat;
background-position: 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); 
}
#banner-divider-second{
background-image: url(/images/second.jpg); 
}