如何为背景图像添加透明度? (HTML + CSS)
How to add transparency to a background image? (HTML + CSS)
我的 CSS 文件中有这些行:
body {
background: url(https://images.freeimages.com/images/large-previews/48d/woodgrain-texture-1151631.jpg);
}
如何使这张图片具有透明度?我找到了一个 "solution",看起来像这样:
img {
opacity: 0.5
}
但我真的不知道如何应用它。如果我只是把它写下来,什么也不会发生,因为我不知道如何将它连接到我想使用的图像。
您只需按如下所示应用它;
body:before {
content: "";
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 1;
background-image: url('https://miro.medium.com/max/1400/1*mk1-6aYaf_Bes1E3Imhc0A.jpeg');
opacity: 0.5;
}
.content {
position: relative;
z-index: 2;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h1 class="content">Hey!</h1>
</body>
</html>
正文是您的背景,内容是您的文字和其他内容等。
您可以利用 background
属性 的 rgba()
功能并将其与 url()
功能结合使用。 RGBA除了Red-Green-Blue之外还有"Alpha"的A,其表现就像opacity
属性;值范围从 0 到 1。在背景图像中使用 RGBA 的技巧是在 linear-gradient()
中使用两个并行的 rgba()
函数。由于 rgba()
returns 一个颜色值,它可以用作线性渐变中的两个色标...尽管从技术上讲它们不是色标,因为两个相似的颜色值不会发生过渡。 Hackish,但简单实用。
body {
background: linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5)),
url('https://images.freeimages.com/images/large-previews/48d/woodgrain-texture-1151631.jpg')
}
我的 CSS 文件中有这些行:
body {
background: url(https://images.freeimages.com/images/large-previews/48d/woodgrain-texture-1151631.jpg);
}
如何使这张图片具有透明度?我找到了一个 "solution",看起来像这样:
img {
opacity: 0.5
}
但我真的不知道如何应用它。如果我只是把它写下来,什么也不会发生,因为我不知道如何将它连接到我想使用的图像。
您只需按如下所示应用它;
body:before {
content: "";
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 1;
background-image: url('https://miro.medium.com/max/1400/1*mk1-6aYaf_Bes1E3Imhc0A.jpeg');
opacity: 0.5;
}
.content {
position: relative;
z-index: 2;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h1 class="content">Hey!</h1>
</body>
</html>
正文是您的背景,内容是您的文字和其他内容等。
您可以利用 background
属性 的 rgba()
功能并将其与 url()
功能结合使用。 RGBA除了Red-Green-Blue之外还有"Alpha"的A,其表现就像opacity
属性;值范围从 0 到 1。在背景图像中使用 RGBA 的技巧是在 linear-gradient()
中使用两个并行的 rgba()
函数。由于 rgba()
returns 一个颜色值,它可以用作线性渐变中的两个色标...尽管从技术上讲它们不是色标,因为两个相似的颜色值不会发生过渡。 Hackish,但简单实用。
body {
background: linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5)),
url('https://images.freeimages.com/images/large-previews/48d/woodgrain-texture-1151631.jpg')
}