在不影响子元素的情况下设置背景图像的不透明度 [英] Set opacity of background image without affecting child elements

查看:25
本文介绍了在不影响子元素的情况下设置背景图像的不透明度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不影响子元素不透明度的情况下设置背景图像的不透明度?

示例

页脚中的所有链接都需要自定义项目符号(背景图片)并且自定义项目符号的不透明度应为 50%.

HTML

CSS

#footer ul li {背景: url(/images/arrow.png) 不重复 0 50%;}

我的尝试

我尝试将列表项的不透明度设置为 50%,但随后链接文本的不透明度也为 50% - 而且似乎没有办法重置子元素的不透明度:

#footer ul li {背景: url(/images/arrow.png) 不重复 0 50%;/* 还将设置链接文本的不透明度 */不透明度:0.5;}

我也尝试过使用 rgba,但这对背景图像没有任何影响:

#footer ul li {/* rgba 不适用于背景图像 */背景:rgba(255, 255, 255, 0.5) url(/images/arrow.png) no-repeat 0 50%;}

解决方案

你可以使用 CSS linear-gradient()rgba().

div {宽度:300px;高度:200px;背景:线性梯度(rgba(255,255,255,.5),rgba(255,255,255,.5)),url(https://i.imgur.com/xnh5x47.jpg");}跨度 {背景:黑色;白颜色;}

<div><span>Hello world.</span></div>

Is it possible to set the opacity of a background image without affecting the opacity of child elements?

Example

All links in the footer need a custom bullet (background image) and the opacity of the custom bullet should be 50%.

HTML

<div id="footer">
    <ul>
        <li><a href="#">Link 1</a></li>
        <li><a href="#">Link 2</a></li>
        <li><a href="#">Link 3</a></li>
        <li><a href="#">Link 4</a></li>
        <li><a href="#">Link 5</a></li>
    </ul>
</div>  

CSS

#footer ul li {
    background: url(/images/arrow.png) no-repeat 0 50%;
}  

What I've Tried

I tried setting the opacity of the list items to 50%, but then the opacity of the link text is also 50% - and there doesn't seem to be a way to reset the opacity of child elements:

#footer ul li {
    background: url(/images/arrow.png) no-repeat 0 50%;
    /* will also set the opacity of the link text */        
    opacity: 0.5;
}

I also tried using rgba, but that doesn't have any effect on the background image:

#footer ul li {
    /* rgba doesn't apply to the background image */
    background: rgba(255, 255, 255, 0.5) url(/images/arrow.png) no-repeat 0 50%;
}

解决方案

You can use CSS linear-gradient() with rgba().

div {
  width: 300px;
  height: 200px;
  background: linear-gradient(rgba(255,255,255,.5), rgba(255,255,255,.5)), url("https://i.imgur.com/xnh5x47.jpg");
}
span {
  background: black;
  color: white;
}

<div><span>Hello world.</span></div>

这篇关于在不影响子元素的情况下设置背景图像的不透明度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆