如何让盒子变成半透明

本指南将帮助你了解使用 CSS 使盒子半透明的方法。

¥This guide will help you to understand the ways to make a box semi-transparent using CSS.

更改框和内容的不透明度

¥Change the opacity of the box and content

如果你希望框和框的所有内容更改不透明度,那么 CSS opacity 属性就是可以使用的工具。不透明度与透明度相反;因此 opacity: 1 是完全不透明的 - 你根本看不到盒子的外面。

¥If you would like the box and all of the contents of the box to change opacity, then the CSS opacity property is the tool to reach for. Opacity is the opposite of transparency; therefore opacity: 1 is fully opaque—you will not see through the box at all.

使用 0 值将使框完全透明,两者之间的值将改变不透明度,值越高透明度越低。

¥Using a value of 0 would make the box completely transparent, and values between the two will change the opacity, with higher values giving less transparency.

仅更改背景颜色的不透明度

¥Changing the opacity of the background color only

在许多情况下,你只想使背景颜色本身部分透明,而使文本和其他元素完全不透明。要实现此目的,请使用具有 Alpha 通道的 <color> 值,例如 rgb()。与 opacity 一样,Alpha 通道值的值为 1 会使颜色完全不透明。因此,background-color: rgb(0 0 0 / 50%); 会将背景颜色设置为 50%不透明度。

¥In many cases you will only want to make the background color itself partly transparent, keeping the text and other elements fully opaque. To achieve this, use a <color> value that has an alpha channel, such as rgb(). As with opacity, a value of 1 for the alpha channel value makes the color fully opaque. Therefore, background-color: rgb(0 0 0 / 50%); will set the background color to 50% opacity.

尝试更改以下示例中的不透明度和 Alpha 通道值,以或多或少地查看框后面的背景图片。

¥Try changing the opacity and alpha channel values in the below examples to see more or less of the background image behind the box.

注意:在覆盖图片的情况下,请注意文本与背景保持足够的对比度;否则可能会使内容难以阅读。

¥Note: Take care that your text retains enough contrast with the background in cases where you are overlaying an image; otherwise you may make the content hard to read.

也可以看看