Độ mờ / Độ trong suốt của CSS
Thuộc opacity
tính chỉ định độ mờ / trong suốt của một phần tử.
Hình ảnh trong suốt
Thuộc opacity
tính có thể nhận giá trị từ 0,0 - 1,0. Giá trị càng thấp, càng minh bạch:
độ mờ 0,2
độ mờ 0,5
opacity 1
(mặc định)
Thí dụ
img {
opacity: 0.5;
}
Hiệu ứng Di chuột trong suốt
Thuộc opacity
tính thường được sử dụng cùng với :hover
bộ chọn để thay đổi độ mờ khi di chuột qua:
Thí dụ
img {
opacity: 0.5;
}
img:hover {
opacity: 1.0;
}
Giải thích ví dụ
Khối CSS đầu tiên tương tự như mã trong Ví dụ 1. Ngoài ra, chúng tôi đã thêm những gì sẽ xảy ra khi người dùng di chuột qua một trong các hình ảnh. Trong trường hợp này, chúng tôi muốn hình ảnh KHÔNG trong suốt khi người dùng di chuột qua nó. CSS cho điều này là opacity:1;
.
Khi con trỏ chuột di chuyển ra khỏi hình ảnh, hình ảnh sẽ trong suốt trở lại.
Một ví dụ về hiệu ứng di chuột đảo ngược:
Thí dụ
img:hover {
opacity: 0.5;
}
Hộp trong suốt
When using the opacity
property to add transparency to the background of an element, all of its child elements
inherit the same transparency. This can make the text inside a fully transparent element hard to read:
opacity 1
opacity 0.6
opacity 0.3
opacity 0.1
Example
div {
opacity: 0.3;
}
Transparency using RGBA
If you do not want to apply opacity to child elements, like in our example above, use RGBA color values. The following example sets the opacity for the background color and not the text:
100% opacity
60% opacity
30% opacity
10% opacity
You learned from our CSS Colors Chapter, that you can use RGB as a color value. In addition to RGB, you can use an RGB color value with an alpha channel (RGBA) - which specifies the opacity for a color.
An RGBA color value is specified with: rgba(red, green, blue, alpha). The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).
Tip: You will learn more about RGBA Colors in our CSS Colors Chapter.
Example
div {
background: rgba(76, 175, 80, 0.3) /* Green background with 30%
opacity */
}
Text in Transparent Box
This is some text that is placed in the transparent box.
Example
<html>
<head>
<style>
div.background {
background: url(klematis.jpg) repeat;
border: 2px solid black;
}
div.transbox {
margin: 30px;
background-color: #ffffff;
border: 1px solid black;
opacity: 0.6;
}
div.transbox p {
margin: 5%;
font-weight: bold;
color: #000000;
}
</style>
</head>
<body>
<div class="background">
<div class="transbox">
<p>This is some text that is placed in the transparent box.</p>
</div>
</div>
</body>
</html>
Example explained
First, we create a <div> element (class="background") with a background image, and a border.
Then we create another <div> (class="transbox") inside the first <div>.
The <div class="transbox"> have a background color, and a border - the div is transparent.
Inside the transparent <div>, we add some text inside a <p> element.