¿Puedo establecer una opacidad solo en la imagen de fondo de un div?


Digamos que tengo

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

Quiero a background-image y opacity de 0.5–, pero quiero que el texto que he escrito tendrá una opacidad completa (1).

Si escribiera el CSS así

.myDiv { opacity:0.5 }

Todo estará en baja opacidad – y no quiero eso.

Entonces, mi pregunta es: ¿Cómo puedo obtener una imagen de fondo de baja opacidad con texto de opacidad completa?

Author: Vadim Ovchinnikov, 2011-08-30

8 answers

No, esto no se puede hacer ya que opacity afecta a todo el elemento incluyendo su contenido y no hay manera de alterar este comportamiento. Puede solucionar esto con los dos métodos siguientes.

División secundaria

Agregue otro elemento div al contenedor para contener el fondo. Este es el método más amigable entre navegadores y funcionará incluso en 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%;
}

Ver caso de prueba en jsFiddle

: antes y:: antes pseudo-elemento

Otro truco es usar los pseudo-elementos CSS 2.1 :before o CSS 3 ::before. El pseudo-elemento :before está soportado en IE desde la versión 8, mientras que el pseudo-elemento ::before no está soportado en absoluto. Se espera que esto se rectifique en la versión 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;
}

Notas adicionales

Debido al comportamiento de z-index tendrá que establecer un índice z para el así como un negativo z-index para la imagen de fondo.

Casos de prueba

Ver caso de prueba en jsFiddle:

 75
Author: mekwall,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-26 14:41:56

Así que aquí hay otra manera:

background-image: linear-gradient(rgba(255,255,255,0.5), rgba(255,255,255,0.5)), url("your_image.png");
 86
Author: GrmXque,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-20 11:05:55

Css

Div {
width: 200px;
height: 200px;
display: block;
posición: relación;
}

Div::después de {
contenido: "";
fondo: url(imagen.jpg);
opacity: 0.5;
top: 0;
left: 0;
bottom: 0;
right: 0;
position: absolute;
z-index: -1;
}

Html


ponga su contenido div

 

 1
Author: Harsukh Makwana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-21 13:04:50

Esto se puede hacer usando la clase div diferente para el texto Hi Allí...

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

Ahora puede aplicar los estilos a la

Etiqueta. de lo contrario, para la clase bg. Estoy seguro de que funciona bien

 0
Author: Supraja Machavaram,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-07 11:08:24

Implementé La solución de Marcus Ekwall pero pude eliminar algunas cosas para hacerlo más simple y todavía funciona. Tal vez la versión 2017 de 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 /

 0
Author: abalter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:17:54

Hola a todos Hice esto y funcionó bien

	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 &amp; WEB</small>
</div>
</section> 
 0
Author: adragom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-12 15:06:08
<!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>

Incluir 4 conjuntos de números lo haría rgba, no cmyk, pero de cualquier manera funcionaría (rgba = 00000088, cmyk= 0%, 0%, 0%, 50%)

 0
Author: villager1,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-29 21:18:48

Ninguna de las soluciones funcionó para mí. Si todo lo demás falla, obtener la imagen a Photoshop y aplicar algún efecto. 5 minutos contra tanto tiempo en esto...

 -1
Author: user2060451,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-14 00:27:43