CSS如何从指定位置开始重复背景?

9
#container{
    background:url(images/bg-main.png) repeat-y;
    width: 903px; 
    background-position: 0px 687px;
    background-position: bottom;
    height: 1200px;
    margin-left: auto;
    margin-right: auto;
    }   
#content{
    background:url(images/bg-wood.png) repeat-y;
    width: 903px; 
    height: 678px;
    margin-left: auto;
    margin-right: auto;
    }

#content div在#container div中。我想让#container的背景从顶部开始重复,距离顶部687像素。这可能吗?

编辑:是否可能让div的前x像素(从顶部开始)为空白空间,并在x像素后开始背景?

3个回答

7
据我所知,您现在尝试的方式是不可能实现repeat-x和repeat-y的,它们会沿着坐标轴在两个方向上重复图像。
如果您将容器背景全长重复,则内容div背景图像是否仍会覆盖前面的678像素?
您能否提供JSFiddle上的代码,以便我们可以看到您尝试实现什么效果?一定会有解决方法的。

5
您可以使用伪元素(::before::after)并利用calc()来实现此目的。
伪元素将为您提供更多控制权,不会影响内容,并且不需要额外的HTML标记。
以下是一个基本示例,距离顶部偏移100px:

.background {
  height: 300px;
  border:1px solid;
  position: relative;
}

.background::before {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  height: calc(100% - 100px);
  width: 100%;
  display: block;
  box-sizing: border-box;
  background: url(//placehold.it/100x100);
}
<div class="background"></div>

您也可以使用相同的技巧从左侧偏移:

.background {
  height: 300px;
  border:1px solid;
  position: relative;
}

.background::before {
  content: '';
  position: absolute;
  bottom: 0;
  right: 0;
  height: 100%;
  width: calc(100% - 100px);
  display: block;
  box-sizing: border-box;
  background: url(//placehold.it/100x100);
}
<div class="background"></div>

甚至可以从两个方向(反向也是如此!):

.background {
  height: 300px;
  border:1px solid;
  position: relative;
}

.background::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  height: calc(100% - 100px);
  width: calc(100% - 100px);
  display: block;
  box-sizing: border-box;
  background: url(//placehold.it/100x100);
}
<div class="background"></div>


1
background : url('image path') 0px 287px repeat-y;

这将使你的背景图像从顶部 287 像素处垂直重复。

但另一种方法是将其设置为你的内容 div:

margin-top:287px;

你最好的解决方案是这样做:

#container{
    position:relative;
    }


#background{
    background:url('image url');
    position:absolute;
    top:287px;
    left:0px;
    z-index:100;
    }  

#content{
    position:absolute;
    top:0px;
    left:0px;
    z-index:99999;
    }

2
你的第一个建议不起作用。287像素 0像素 - 这里的第一个值是水平位置,不是垂直位置。 但是,第二个解决方案似乎可以,我将不得不使用jQuery来定义它的高度。 - ilija veselica
1
background : url('image path') 0px 287px repeat-y; 这是我已经尝试过的(你可以查看我的问题(第2行和第4行)- 但它不起作用 :)。 - ilija veselica
使用最后一个解决方案。我为您编写了一个示例。 - Farzin Zaker
3
第一个解决方案是不正确的,不应该作为答案的一部分保留。 - johncip
第一部分需要被移除。 - Adrian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接