我可以只为 div 的背景图像设置不透明度吗?

发布于 2024-12-02 05:24:01 字数 393 浏览 0 评论 0原文

假设我

<div class="myDiv">Hi there</div>

想放置一个背景图像并为其设置不透明度0.5 - 但我希望我写的文本将具有完全不透明度 (1)。

如果我像这样编写 CSS

.myDiv { opacity:0.5 }

所有内容都将处于低不透明度 - 我不希望这样。

所以我的问题是 - 如何获得具有完全不透明文本的低不透明度背景图像?

Let's say I have

<div class="myDiv">Hi there</div>

I want to put a background-image and give it an opacity of 0.5 – but I want that the text I have written will have full opacity (1).

If I would write the CSS like this

.myDiv { opacity:0.5 }

everything will be in low opacity – and I don't want that.

So my question is – How can I get low-opacity background image with full opacity text?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

一梦浮鱼 2024-12-09 05:24:01

所以这是另一种方法:

background-image: linear-gradient(rgba(255,255,255,0.5), rgba(255,255,255,0.5)), url("your_image.png");

So here is an other way:

background-image: linear-gradient(rgba(255,255,255,0.5), rgba(255,255,255,0.5)), url("your_image.png");
同尘 2024-12-09 05:24:01

不,这是无法完成的,因为 opacity 会影响整个元素(包括其内容),并且无法更改此行为。您可以通过以下两种方法解决此问题。

辅助 div

将另一个 div 元素添加到容器中以容纳背景。这是跨浏览器最友好的方法,甚至可以在 IE6 上运行。

HTML

<div class="myDiv">
    <div class="bg"></div>
    Hi there
</div>

CSS

.myDiv {
    position: relative;
    z-index: 1;
}

.myDiv .bg {
    position: absolute;
    z-index: -1;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: url(test.jpg) center center;
    opacity: .4;
    width: 100%;
    height: 100%;
}

请参阅jsFiddle 上的测试用例

: before 和 ::before 伪元素

另一个技巧是使用 CSS 2.1 :before 或 CSS 3 ::before 伪元素。 IE 从版本 8 开始支持 :before 伪元素,而 ::before 伪元素根本不支持。这有望在版本 10 中得到纠正。

HTML

<div class="myDiv">
    Hi there
</div>

CSS

.myDiv {
    position: relative;
    z-index: 1;
}

.myDiv:before {
    content: "";
    position: absolute;
    z-index: -1;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: url(test.jpg) center center;
    opacity: .4;
}

附加说明

由于 z-index 的行为,您必须设置 z-容器的索引以及背景图像的负 z-index

测试用例

请参阅 jsFiddle 上的测试用例:

Nope, this cannot be done since opacity affects the whole element including its content and there's no way to alter this behavior. You can work around this with the two following methods.

Secondary div

Add another div element to the container to hold the background. This is the most cross-browser friendly method and will work even on IE6.

HTML

<div class="myDiv">
    <div class="bg"></div>
    Hi there
</div>

CSS

.myDiv {
    position: relative;
    z-index: 1;
}

.myDiv .bg {
    position: absolute;
    z-index: -1;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: url(test.jpg) center center;
    opacity: .4;
    width: 100%;
    height: 100%;
}

See test case on jsFiddle

:before and ::before pseudo-element

Another trick is to use the CSS 2.1 :before or CSS 3 ::before pseudo-elements. :before pseudo-element is supported in IE from version 8, while the ::before pseudo-element is not supported at all. This will hopefully be rectified in version 10.

HTML

<div class="myDiv">
    Hi there
</div>

CSS

.myDiv {
    position: relative;
    z-index: 1;
}

.myDiv:before {
    content: "";
    position: absolute;
    z-index: -1;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: url(test.jpg) center center;
    opacity: .4;
}

Additional notes

Due to the behavior of z-index you will have to set a z-index for the container as well as a negative z-index for the background image.

Test cases

See test case on jsFiddle:

甜柠檬 2024-12-09 05:24:01

html

div { 
    width: 200px;
    height: 200px;
    display: block;
    position: relative;
}

div::after {
    content: "";
    background: url(image.jpg); 
    opacity: 0.5;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    position: absolute;
    z-index: -1;
}

<div> put your div content</div>

css

div { 
    width: 200px;
    height: 200px;
    display: block;
    position: relative;
}

div::after {
    content: "";
    background: url(image.jpg); 
    opacity: 0.5;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    position: absolute;
    z-index: -1;
}

html

<div> put your div content</div>
木落 2024-12-09 05:24:01

我实现了 Marcus Ekwall 的解决方案,但删除了一些内容以使其更简单,并且仍然有效。也许是 2017 版本的 html/css?

html:

<div id="content">
  <div id='bg'></div>
  <h2>What is Lorem Ipsum?</h2>
  <p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
    book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
    desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>

css:

#content {
  text-align: left;
  width: 75%;
  margin: auto;
  position: relative;
}

#bg {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: url('https://static.pexels.com/photos/6644/sea-water-ocean-waves.jpg') center center;
  opacity: .4;
  width: 100%;
  height: 100%;
}

https://jsfiddle.net/abalter/3te9fjL5/

I implemented Marcus Ekwall's solution but was able to remove a few things to make it simpler and it still works. Maybe 2017 version of html/css?

html:

<div id="content">
  <div id='bg'></div>
  <h2>What is Lorem Ipsum?</h2>
  <p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
    book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
    desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>

css:

#content {
  text-align: left;
  width: 75%;
  margin: auto;
  position: relative;
}

#bg {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: url('https://static.pexels.com/photos/6644/sea-water-ocean-waves.jpg') center center;
  opacity: .4;
  width: 100%;
  height: 100%;
}

https://jsfiddle.net/abalter/3te9fjL5/

我爱人 2024-12-09 05:24:01

大家好,我这样做了,效果很好

	var canvas, ctx;

		function init() {
			canvas = document.getElementById('color');
			ctx = canvas.getContext('2d');

			ctx.save();
			ctx.fillStyle = '#bfbfbf'; //  #00843D   // 118846
			ctx.fillRect(0, 0, 490, 490);
			ctx.restore();
		}
section{
		height: 400px;
		background: url(https://images.pexels.com/photos/265087/pexels-photo-265087.jpeg?w=1260&h=750&auto=compress&cs=tinysrgb);
		background-repeat: no-repeat;
		background-position: center;
		background-size: cover;
		position: relative;
	
}

canvas {
	width: 100%;
	height: 400px;
	opacity: 0.9;

}

#text {
	position: absolute;
	top: 10%;
	left: 0;
	width: 100%;
	text-align: center;
}


.middle{
	text-align: center;
	
}

section small{
	background-color: #262626;
	padding: 12px;
	color: whitesmoke;
  letter-spacing: 1.5px;

}

section i{
  color: white;
  background-color: grey;
}

section h1{
  opacity: 0.8;
}
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Metrics</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">  
</head>  
  
<body onload="init();">
<section>
<canvas id="color"></canvas>

<div class="w3-container middle" id="text">
<i class="material-icons w3-highway-blue" style="font-size:60px;">assessment</i>
<h1>Medimos las acciones de tus ventas y disenamos en la WEB tu Marca.</h1>
<small>Metrics & WEB</small>
</div>
</section> 

Hello to everybody I did this and it worked well

	var canvas, ctx;

		function init() {
			canvas = document.getElementById('color');
			ctx = canvas.getContext('2d');

			ctx.save();
			ctx.fillStyle = '#bfbfbf'; //  #00843D   // 118846
			ctx.fillRect(0, 0, 490, 490);
			ctx.restore();
		}
section{
		height: 400px;
		background: url(https://images.pexels.com/photos/265087/pexels-photo-265087.jpeg?w=1260&h=750&auto=compress&cs=tinysrgb);
		background-repeat: no-repeat;
		background-position: center;
		background-size: cover;
		position: relative;
	
}

canvas {
	width: 100%;
	height: 400px;
	opacity: 0.9;

}

#text {
	position: absolute;
	top: 10%;
	left: 0;
	width: 100%;
	text-align: center;
}


.middle{
	text-align: center;
	
}

section small{
	background-color: #262626;
	padding: 12px;
	color: whitesmoke;
  letter-spacing: 1.5px;

}

section i{
  color: white;
  background-color: grey;
}

section h1{
  opacity: 0.8;
}
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Metrics</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">  
</head>  
  
<body onload="init();">
<section>
<canvas id="color"></canvas>

<div class="w3-container middle" id="text">
<i class="material-icons w3-highway-blue" style="font-size:60px;">assessment</i>
<h1>Medimos las acciones de tus ventas y disenamos en la WEB tu Marca.</h1>
<small>Metrics & WEB</small>
</div>
</section> 

画离情绘悲伤 2024-12-09 05:24:01

由于布局如何变化以及跟踪是多么不切实际,使用具有 100% 宽度和高度的内部绝对元素的方法对我来说不起作用。

所以我想出了一个解决办法;使用设置的 Alpha 将图像渲染到画布,然后从画布获取 Blob URL。

async function generateDataUrlFromImage(src: string, opacity: number) {
  return new Promise(async (resolve) => {
    const img = document.createElement('img');
    img.src = src;
    await img.decode();
    const canvas = document.createElement('canvas');
    canvas.width = img.naturalWidth;
    canvas.height = img.naturalHeight;
    const ctx = canvas.getContext('2d')!;
    ctx.globalAlpha = opacity / 100;
    ctx.drawImage(img, 0, 0);
    canvas.toBlob((blob) => {
      resolve(URL.createObjectURL(blob!));
    });
  });
}

不是最有效的,但它在布局方面是万无一失的,因为您确实可以使用背景图像。对于其他图像来说,它的性能可能不够,我需要使用的图像是一个小的 150x150px 图案,所以它已经足够好了;我把它放在大约 20 毫秒处。

The approach of using an inner absolute element with 100% width and height didn't work for me due to how the layout changed and the how impractical it was to keep track.

So I came up with a solution; rendering the image to a canvas with a set alpha, and then getting a blob URL from the canvas.

async function generateDataUrlFromImage(src: string, opacity: number) {
  return new Promise(async (resolve) => {
    const img = document.createElement('img');
    img.src = src;
    await img.decode();
    const canvas = document.createElement('canvas');
    canvas.width = img.naturalWidth;
    canvas.height = img.naturalHeight;
    const ctx = canvas.getContext('2d')!;
    ctx.globalAlpha = opacity / 100;
    ctx.drawImage(img, 0, 0);
    canvas.toBlob((blob) => {
      resolve(URL.createObjectURL(blob!));
    });
  });
}

Not the most efficient, but it's foolproof in terms of layout since you can really use background-image. It might not be performant enough for other images, the image that I needed to use was a small 150x150px pattern so it's good enough; I benched it at about 20ms.

千里故人稀 2024-12-09 05:24:01

这可以通过对文本 Hi There... 使用不同的 div 类来完成。

<div class="myDiv">
    <div class="bg">
   <p> Hi there</p>
</div>
</div>

现在您可以将样式应用到

标签。否则对于 bg 类。
我确信它工作得很好

This can be done by using the different div class for the text Hi There...

<div class="myDiv">
    <div class="bg">
   <p> Hi there</p>
</div>
</div>

Now you can apply the styles to the

tag. otherwise for bg class.
I am sure it works fine

你的笑 2024-12-09 05:24:01

这些解决方案都不适合我。如果一切都失败了,请将图片放入 Photoshop 并应用一些效果。 5分钟与这么多时间相比......

None of the solutions worked for me. If everything else fails, get the picture to Photoshop and apply some effect. 5 minutes versus so much time on this...

挽清梦 2024-12-09 05:24:01
<!DOCTYPE html>
<html>
<head></head>
<body>
<div style=" background-color: #00000088"> Hi there </div>
<!-- #00 would be r, 00 would be g, 00 would be b, 88 would be a. -->
</body>
</html>

包含 4 组数字将使其成为 rgba,而不是 cmyk,但任何一种方式都可以(rgba= 00000088,cmyk= 0%, 0%, 0%, 50%)

<!DOCTYPE html>
<html>
<head></head>
<body>
<div style=" background-color: #00000088"> Hi there </div>
<!-- #00 would be r, 00 would be g, 00 would be b, 88 would be a. -->
</body>
</html>

including 4 sets of numbers would make it rgba, not cmyk, but either way would work (rgba= 00000088, cmyk= 0%, 0%, 0%, 50%)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文