可以在CSS中设置边框不透明度吗? [英] Can you set a border opacity in CSS?

查看:493
本文介绍了可以在CSS中设置边框不透明度吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有直接的CSS方法使元素的边框像这样半透明?

Is there a straight forward CSS way to make the border of an element semi-transparent with something like this?

border-opacity: 0.7;

如果没有,有没有人知道我不使用图像怎么办?

If not, does anyone have an idea how I could do so without using images?

推荐答案

不幸的是,opacity元素使整个元素(包括任何文本)都是半透明的.使边框半透明的最佳方法是使用rgba颜色格式.例如,这将给出不透明度为50%的红色边框:

Unfortunately the opacity element makes the whole element (including any text) semi-transparent. The best way to make the border semi-transparent is with the rgba color format. For example, this would give a red border with 50% opacity:

div {
    border: 1px solid rgba(255, 0, 0, .5);
    -webkit-background-clip: padding-box; /* for Safari */
    background-clip: padding-box; /* for IE9+, Firefox 4+, Opera, Chrome */
}

此方法的问题在于某些浏览器不理解rgba格式,如果这是整个声明,则根本不会显示任何边框.解决方案是提供两个边界声明.第一个具有假的不透明性,第二个具有实际的不透明性.如果浏览器有能力,它将使用第二个浏览器,否则将使用第一个.

The problem with this approach is that some browsers do not understand the rgba format and will not display any border at all if this is the entire declaration. The solution is to provide two border declarations. The first with a fake opacity, and the second with the actual. If a browser is capable, it will use the second, if not, it will use the first.

div {
    border: 1px solid rgb(127, 0, 0);
    border: 1px solid rgba(255, 0, 0, .5);
    -webkit-background-clip: padding-box; /* for Safari */
    background-clip: padding-box; /* for IE9+, Firefox 4+, Opera, Chrome */
}

第一个边框声明将与白色背景上50%不透明的红色边框具有相同的颜色(尽管边框下的任何图形都不会渗出).

The first border declaration will be the equivalent color to a 50% opaque red border over a white background (although any graphics under the border will not bleed through).

更新:我添加了"background-clip:padding-box;"对此答案(按照SooDesuNe在评论中的建议)进行操作,以确保即使应用纯色背景,边框也保持透明.

UPDATE: I've added "background-clip: padding-box;" to this answer (per SooDesuNe's suggestion in the comments) to ensure the border remains transparent even if a solid background color is applied.

这篇关于可以在CSS中设置边框不透明度吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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