The transparency of the color can be set through rgba() and hsla(), but they can only set the transparency when defining the color, and cannot set the transparency for images or other elements.
Two ways to set transparency with CSS:
1. CSS rgba() sets color transparency
grammar:
rgba(R,G,B,A);
RGBA is the abbreviation for the three words Red (red) Green (green) Blue (blue) and Alpha (opacity). RGBA color values are an extension of RGB color values, with an alpha channel - which specifies the object's opacity.
Introduction to the values in rgba():
R: red value. Positive integer (0~255)
G: green value. Positive integer (0~255)
B: blue value. Positive integer (0~255)
A: Transparency. The value is between 0~1
rgba() can simply set the color transparency, which has many applications in page layout. For example: make the background transparent, but the text above is opaque.
Example:
<!DOCTYPEhtml><html><head><metacharset=UTF-8><title>dotcpp programming</title><style>.demo{width:350px;height:300px;margin:50pxauto;}.demo*{width :120px;height:120px;mar gin:10px;float:left;}.demo1{background:rgba(255,0,0,1);}.demo2{background:rgba(255,0,0,0.5);}</style></head ><body><divclass=demo><divclass=demo1>The background color is opaque and the text is opaque! </div><divclass=demo2>The background color is semi-transparent and the text is opaque! </div></div></body></html>
Running results:
In the above example, the color values set are the same, but the transparency is different.
2. CSS opacity attribute sets background transparency
grammar:
opacity:value;
value: Specifies the opacity, from 0.0 (fully transparent) to 1.0 (fully opaque).
The opacity attribute is inherited and will make all elements in the container transparent;
Example:
<!DOCTYPEhtml><html><head><metacharset=UTF-8><title>opacity attribute</title><style>.demo{width:280px;height:140px;margin:50pxauto;}.demo1,.demo2 {width:120px;height :120px;margin:10px;float:left;background:#2DC4CB;}.demo1{opacity:1;}.demo2{opacity:0.5;}</style></head><body><divclass=demo>< divclass=demo1><p>The background color is opaque and the text is opaque! </p></div><divclass=demo2><p>The background color is transparent and the text is also transparent! </p></div></div></body></html>
Running results:
Opacity:0.5; makes all elements of the demo2 container translucent.
Summary: Although both the rgba() method and the opacity method can achieve transparency effects, rgba() only acts on the color of the element or its background color (the child elements of the element with rgb() transparency set will not inherit its transparency effect); and Opacity is inherited, not only affects the element itself, but also makes all sub-elements within the element transparent.