使用 CSS 在列表中的背景颜色上方制作背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8491958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 02:22:26  来源:igfitidea点击:

Use CSS to make background-image above background-color in a list

cssz-indexbackground-imagebackground-color

提问by user826224

This is the code

这是代码

<ul>
    <li class="test">
         <a href="#">
            <h2>Blah</h2>
            <p>Blah Blah Blah</p>
         </a>
    </li>
</ul>

Basically, my list already has some styling, for example, I set the background-color for it.

基本上,我的列表已经有了一些样式,例如,我为它设置了背景颜色。

Now in the class "test", I also set a background-image.

现在在“测试”类中,我还设置了背景图像。

My question is I want to make the background-image stays above the background-color and I dont know how to achieve this. I tried with z-index but I think it is not applicable for background-image.

我的问题是我想让背景图像保持在背景颜色之上,我不知道如何实现这一点。我尝试使用 z-index,但我认为它不适用于背景图像。

Please take a look at the image

请看一下图片

Output

输出

Edit: This is the CSS Code

编辑:这是 CSS 代码

For example, this is the styling for my list

例如,这是我列表的样式

#sidebar ul li{  
    background:#ccf;
}

And this is the styling for the class test

这是课堂测试的样式

.test{
    background-image: url('img/big_tick.png');
    background-repeat:no-repeat;
    background-position: bottom right;
    -moz-background-size: 30%;
    -webkit-background-size: 30%;
    background-size: 30%;    
    margin-right: 30px;
}

采纳答案by piebie

Add the !importantattribute to your background-image. Like this:

!important属性添加到您的background-image. 像这样:

.test a{
background-image: url('img/big_tick.png') !important;
background-repeat:no-repeat;
background-position: bottom right;
-moz-background-size: 30%;
-webkit-background-size: 30%;
background-size: 30%;    
margin-right: 30px;

}

}

I have an example fiddle here

这里有一个小提琴示例

EDIT: I changed the class to .test ato reflect the actual styling scheme

编辑:我改变了类.test a以反映实际的样式方案

回答by shaunsantacruz

Try: adding specificity to the .test class: #sidebar ul li.test

尝试:向 .test 类添加特异性: #sidebar ul li.test

Or, better yet, if it's possible, add background-colorto the .test class, and get rid of the element selector altogether.

或者,更好的是,如果可能的话,添加background-color到 .test 类,并完全摆脱元素选择器。

I would avoid using !important unless you absolutely need it. In the long run, using it will make editing your css a pain. Instead of using !important, I suggest learning about specificity: http://reference.sitepoint.com/css/inheritancecascade

我会避免使用 !important 除非你绝对需要它。从长远来看,使用它会使编辑 css 变得痛苦。我建议不要使用 !important,而是建议了解特异性:http: //reference.sitepoint.com/css/inheritancecascade