【问题标题】:Defining background gradient in one class and background image in another?在一个类中定义背景渐变,在另一个类中定义背景图像?
【发布时间】:2015-06-07 05:57:30
【问题描述】:

我正在使用以下 CSS 块来定义应用于许多不同背景图像的渐变:

.myDiv{
    background: linear-gradient(to right,  rgba(0,0,0,1) 0%,rgba(0,0,0,0.01) 28%), url(myimage.png);
}

问题是我有大约 10 个 div 将使用此渐变。有没有办法在一个类中定义渐变,在另一个类中定义背景,这样我的代码就不会那么冗长了?我试过了:

.myGradient{
   background: linear-gradient(to right,  rgba(0,0,0,1) 0%,rgba(0,0,0,0.01) 28%);
}
.myDiv{
    background-image: url(myimage.png);
}

然后将这两个类应用于我的 div,但无济于事。是否可以将渐变 css 与图像 url 分开?

【问题讨论】:

  • 听起来类似于this one。总之,没有直接的方法。您还可以查看一些预处理器,例如 Less,它们可以帮助处理合并语法,但编译后的 CSS 仍然会很大。

标签: html css


【解决方案1】:

我认为不可能将它们分开,因为渐变和图像都是background-image 值。如果您在不同的类中使用它们,一个或另一个将覆盖另一个。

在我看来,另一种方法是使用一些照片编辑工具将渐变+图像的精灵放在一起,并通过使用 background-position 在 10 div 中使用它们。

另一种方法是像这样使用pseudo 类:

CSS:

div {
    width:300px;
    height:300px;
    background-repeat:no-repeat;
    position:relative;
    background-size:cover;
}
div:after {
    background-image:linear-gradient(to right, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 0.01) 28%);
    ;
    content:"";
    top:0;
    left:0;
    right:0;
    bottom:0;
    position:absolute;
}
.div1 {
    background-image: url(http://www.lorempixel.com/600/200/sports/1/);
}
.div2 {
    background-image: url(http://www.lorempixel.com/600/200/sports/2/);
}
.div3 {
    background-image: url(http://www.lorempixel.com/600/200/sports/3/);
}
.div4 {
    background-image: url(http://www.lorempixel.com/600/200/sports/4/);
}
.div5 {
    background-image: url(http://www.lorempixel.com/600/200/sports/5/);
}
.div6 {
    background-image: url(http://www.lorempixel.com/600/200/sports/6/);
}
.div7 {
    background-image: url(http://www.lorempixel.com/600/200/sports/7/);
}
.div8 {
    background-image: url(http://www.lorempixel.com/600/200/sports/8/);
}
.div9 {
    background-image: url(http://www.lorempixel.com/600/200/sports/9/);
}
.div10 {
    background-image: url(http://www.lorempixel.com/600/200/sports/10/);
}

HTML:

<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
<div class="div4"></div>
<div class="div5"></div>
<div class="div6"></div>
<div class="div7"></div>
<div class="div8"></div>
<div class="div9"></div>
<div class="div10"></div>

演示:http://jsfiddle.net/lotusgodkk/GCu2D/738/

【讨论】:

  • 是否可以像这样使用两个分层的背景图像:`背景图像:,url(); `?
  • 是的,你可以看看演示
【解决方案2】:

有点话题-但也许足够有趣...

如果您使用 less (>= v1.5.0),您可以使用 property merging with the plus operator

最后还是一样,CSS没有提供这样的功能(我认为)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    相关资源
    最近更新 更多