CSS不透明度
时间:2020-02-23 14:30:12 来源:igfitidea点击:
在本教程中,我们将学习CSS不透明度。
不透明
我们使用" opacity"属性来控制元素的不透明度。
此属性的取值范围为0到1。
因此,0表示完全透明。
1表示100%不透明。
同样,0.5表示50%透明。
元素的不透明度值也将由其子元素继承。
在下面的示例中,我们将div的不透明度设置为不同的值。
/**
* common for the divs
*/
div {
background-color : #0f0;
color : #333;
padding : 20px 5px;
text-align : center;
float : left;
margin-left : 20px;
width : 100px;
height : 50px;
opacity : 1;
}
/**
* for respective opacity
*/
div#box-1 {
opacity : 1;
}
div#box-2 {
opacity : 0.7;
}
div#box-3 {
opacity : 0.5;
}
div#box-4 {
opacity : 0.2;
}
div#box-5 {
opacity : 0;
}
使用RGBA的不透明度
我们还可以使用background属性将元素的不透明度设置为rgba()。
在这种情况下,应用于元素的不透明度值不会被其子元素继承。
rgba()采用4个逗号分隔的值,第四个值用于不透明度。
单击此处获取CSS Color教程,并阅读有关RGBA的信息。
在以下示例中,我们使用rgba值设置了div的不透明度。
/**
* common for the divs
*/
div {
color : #333;
padding : 20px 5px;
text-align : center;
float : left;
margin-left : 20px;
width : 100px;
height : 50px;
opacity : 1;
}
/**
* for respective opacity
*/
div#box-1 {
background : rgba(0, 255, 0, 1);
}
div#box-2 {
background : rgba(0, 255, 0, 0.7);
}
div#box-3 {
background : rgba(0, 255, 0, 0.5);
}
div#box-4 {
background : rgba(0, 255, 0, 0.2);
}
div#box-5 {
background : rgba(0, 255, 0, 0);
}
IE过滤器
对于IE8和更早的版本,我们使用filter属性,并将其值设置为alpha(opacity = X)。
变量X的取值范围为0到100。
其中100表示完全不透明,0表示完全透明。
在下面的示例中,我们设置了不透明度和过滤器(对于IE 8或者更早版本)。
div {
opacity : 0.5;
filter : alpha(opacity=50);
color : #333;
background-color : #0f0;
padding : 20px 5px;
text-align : center;
margin-left : 20px;
}
不透明和悬停
当鼠标悬停在元素上时,我们可以使用:hover来改变元素的不透明度。
在下面的示例中,当鼠标悬停在div上方时,其不透明度更改为50%。
div {
color : #333;
background-color : #0f0;
padding : 20px 5px;
text-align : center;
margin-left : 20px;
}
div:hover {
opacity : 0.5;
filter : alpha(opacity=50);
}
在下面的示例中,当鼠标悬停在图像上方时,其不透明度更改为10%。
img:hover {
opacity : 0.1;
filter : alpha(opacity=10);
}

