多种背景颜色、图片在CSS中的应用方法

7
我该如何在CSS中将单个
元素多次背景颜色或图像?例如,我希望顶部是红色的,然后中间是蓝色的,底部是绿色的。

2
嗨,请看一下这个线程。https://dev59.com/Amw15IYBdhLWcg3wtNyO#6457484 - cdslijngard
4个回答

6
一个 linear-gradient 作为背景就足够了。
background: linear-gradient(to bottom, 
    red 0, red 33.33%, 
    blue 0, blue 66.66%, 
    green 0, green 100%
);

示例 | 浏览器支持


好的。你能解释一下没有百分号的0是做什么用的吗? - Nathan Arthur
1
这是颜色停止位置的工作原理:当您设置一个值低于前面定义的颜色停止位置时,它会自动设置为前面最大的值。因此,写作red 0、red 33.33%、blue 33.33%、blue 66.66%、green 66.66%、green 100%等同于但较少重复值(例如,如果您将66.66更改为80%,则必须更改两次该值)。 - Fabrizio Calderan

2

使用CSS3中的渐变。

YourDIVID {
  background: red; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(red, yellow, green); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(red, yellow, green); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(red, yellow, green); /* For Firefox 3.6 to 15 */
  background: linear-gradient(red, yellow, green); /* Standard syntax */
} 

1

单行文本的顶部、底部、中心多颜色教程

#multiple {
width: 700px;
height: 500px;
background:linear-gradient(red, yellow, green, blue, purple, orange);

}


0

使用 :before:after 伪元素规则 在单个元素上拥有三个不同的背景层(颜色和图像)。

注意:此解决方案需要将包含的元素包装在上面以保持在背景之上。否则,链接可能无法点击,文本无法选择等。

运行代码片段以获得可工作的示例。

.layered-backgrounds {
  background-color: #C63;
  background-image: url(https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png);
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
  position: relative;
  height: 400px;
  z-index: 1;
}

.layered-backgrounds:before {
  position: absolute;
  content: " ";
  top: 0;
  height: 120px;
  width: 100%;
  background: #39C;
  z-index: 2;
  opacity: 0.8;
}

.layered-backgrounds:after {
  position: absolute;
  content: " ";
  bottom: 0;
  height: 120px;
  width: 100%;
  background: #9C3;
  z-index: 3;
  opacity: 0.8;
}

.layered-backgrounds .content {
    position: relative;
    z-index: 4;
}
<div class="layered-backgrounds">
    <div class="content">
        <a href="#">Clickable</a> and selectable contents.
    </div>
</div>


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