如何使用背景图像排列几个div

时间:2013-12-23 16:33:35

标签: css background-image

我有一个非常大的图像用作背景图像。因为图像太大,我把它分成三个图像,可以一个堆叠在另一个上面。

我将图像作为背景图像放入“cover”属性:

<div class="screen" id="header1"></div>
<div class="screen" id="header2"></div>
<div class="screen" id="header3"></div> 

的CSS:

#header1
{
    background-color: #000;
    width: 100%;
    height: 100%;
    max-width: 1920px;
   max-height: 949px;
   background: url('images/bg1_landscape2.png') no-repeat center center; 
   background-size:cover;
  -webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
padding: 0;
margin: 0;

}

#header2
{
    background-color: #000;
    width: 100%; 
    max-width: 1920px;
   height: 100%; 
   max-height: 947px;
   background: url('images/bg2_landscape2.png') no-repeat center center; 
   background-size:cover;
   -webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;padding: 0;
margin: 0;

}
#header3
{
    background-color: #000;
    width: 100%; 
    height: 100%; 
   max-width: 1920px;
   background: url('images/bg3_landscape2.png') no-repeat center center; 
   background-size:cover;
   -webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
padding: 0;
margin: 0;
}

问题是背景图像中的图案不对齐。

无论屏幕有多宽,如何将多个背景图像对齐?

1 个答案:

答案 0 :(得分:0)

所以...这里有一些事情要做:

第一个问题:您还没有做任何事情来使CSS在CSS中重叠,因此它们将在文档流程中一个接一个地出现浏览器。例如,查看此小提琴here

div:first-child {
    background: red;
}
div {
    background: green;
    width: 100%;
    height: 100%;
}
div:last-child {
    background: blue;
}

如果你希望它们完全重叠,也就是叠加,那么它们需要绝对位于彼此之上,如下所示:

div:first-child {
    background: red;
}

div {
    background: green;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}

div:last-child {
    background: blue;
}

另一个问题是您将大背景图片分成3个较小图像的原因。我们将其称为图像切片,这实际上并不是最佳的。它需要3个http请求而不是一个来检索该图像,这比仅仅经常获得较小的一个更开销。此外,它是一个背景图像,因此它不会像图像内嵌图像那样阻止文档完全加载,直到图像加载为止。

希望这有帮助。