【问题标题】:CSS: Is it possible to repeat only part of an image to use it as a background?CSS:是否可以仅重复图像的一部分以将其用作背景?
【发布时间】:2009-08-08 22:07:55
【问题描述】:

我有一个圆角矩形的图像,我将它用于背景的顶部和底部,方法是:

#content_top { /* 760px by 30px */
    background: #F7EECF url(images/content_top_bottom_bg.png) no-repeat 0 0 scroll;
    height: 10px;
}

#content_bottom { /* 760px by 30px */
    background: #F7EECF url(images/content_top_bottom_bg.png) no-repeat 0 -20px scroll;
    height: 10px;
}

然后我使用另一个 1px 高度的图像垂直重复以填充该 div 背景之间的区域。像这样:

#content { /* 760px by 1px */
    background: #F7EECF url(images/content_body.png) repeat-y 0 0 scroll;
}

现在我想知道是否可以只使用相同的图像 (content_top_bottom.png),但只使用其中的一部分来达到相同的效果?我尝试了类似的方法,但没有成功:

#content { /* 760px by 1px */
    background: #F7EECF url(images/content_top_bottom.png) repeat-y 0 -5px scroll;
}

我想使用相同的图像,因为我想减少 http 请求的数量。 1px 的图像可能不会产生很大的影响,但我只是想尝试一下。有人可以帮忙吗?

【问题讨论】:

    标签: html css background


    【解决方案1】:

    通过将顶部、中间和底部部分并排放置,制作 2280 x 10 的图像。然后你可以重复中间部分:

    #content_top {
      background: #F7EECF url(images/content_bg.png) no-repeat 0 0 scroll;
      height: 10px;
    }
    
    #content {
      background: #F7EECF url(images/content_bg.png) repeat-y -760px 0 scroll;
    }
    
    #content_bottom {
      background: #F7EECF url(images/content_bg.png) no-repeat -1520px 0 scroll;
      height: 10px;
    }
    

    【讨论】:

    • +1:很好!删除我的答案(表示无法完成)。
    • 为什么投反对票?如果你不说你不喜欢什么,那是相当没有意义的......
    【解决方案2】:

    我建议在整个网站上使用 3 张图片:

    1. 标准非重复精灵。在您的情况下,这将是 content_top_bottom.png(尽管重命名它可能会更好,以便它更通用并且可以用于其他部分)。
    2. “repeat-x”图像。这将是一个 1 像素宽的图像(或多一点,取决于设计)但非常高。您将在其中放置所有水平重复的图像。
    3. “repeat-y”图像,类似于 #2,除了 1 像素高和非常宽。您可以在此处放置您的 content_body.png 图片。

    尽管在您当前的情况下,这会产生 2 个 HTTP 请求,但它的可扩展性要高得多,因为您不会使用超过 3 个。不幸的是,对于两个方向平铺的背景,它们必须是单独的。

    您可能也有兴趣阅读 CSS3 属性 border-image,它允许您将一张图像用于一个完整的元素。它还没有得到很好的支持,但希望它不会太长

    【讨论】:

      猜你喜欢
      • 2021-09-22
      • 2011-07-30
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      • 2016-10-13
      相关资源
      最近更新 更多