Могу ли я установить непрозрачность только для фонового изображения div? - PullRequest
68 голосов
/ 30 августа 2011

Допустим, у меня есть

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

Я хочу поставить background-image и дать ему opacity 0.5 - но я хочу, чтобы текст, который я написал, имел полную непрозрачность1).

Если бы я написал CSS так, как это

.myDiv { opacity:0.5 }

, то все будет с низкой непрозрачностью - и я не хочу этого.Поэтому мой вопрос - как мне получить фоновое изображение с низкой непрозрачностью и текстом с полной непрозрачностью?

Ответы [ 8 ]

112 голосов
/ 16 декабря 2014

Так вот другой способ:

background-image: linear-gradient(rgba(255,255,255,0.5), rgba(255,255,255,0.5)), url("your_image.png");
83 голосов
/ 30 августа 2011

Нет, это невозможно сделать, поскольку 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 псевдоэлементы.Псевдоэлемент :before поддерживается в IE начиная с версии 8, тогда как псевдоэлемент ::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:

2 голосов
/ 21 ноября 2014

1001 * 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>
0 голосов
/ 30 марта 2018
<!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%)

0 голосов
/ 12 марта 2018

Привет всем, я сделал это, и это сработало хорошо

	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 голосов
/ 12 мая 2017

Я реализовал Решение Маркуса Эквалла , но смог удалить несколько вещей, чтобы сделать его проще, и он все еще работает.Может быть, версия html / css 2017 года?

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 голосов
/ 14 октября 2016

Ни одно из решений не сработало для меня. Если ничего не помогло, перенесите картинку в Photoshop и примените некоторый эффект. 5 минут против такого времени на этом ...

0 голосов
/ 07 января 2015

Это можно сделать с помощью другого класса div для текста Hi There ...

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

Теперь вы можете применять стили к тегу

.в противном случае для класса BG.Я уверен, что он отлично работает

...