4

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

每当我使用以下代码时,它都可以正常工作,显然:

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

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

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

我究竟做错了什么?

4

2 回答 2

8

您正在覆盖整个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>

于 2016-03-09T10:28:05.807 回答
1

您需要使用背景图像而不是使用背景属性。

.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); 
}
于 2016-03-09T10:29:21.110 回答