Подтвердить что ты не робот

Могу ли я установить непрозрачность только на фоновое изображение div?

Скажем, у меня есть

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

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

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

.myDiv { opacity:0.5 }

все будет в низкой непрозрачности - и я не хочу этого.

Поэтому мой вопрос: как получить фоновое изображение с низкой непрозрачностью с полным текстом непрозрачности?

4b9b3361

Ответ 1

Нет, это невозможно сделать, поскольку 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

: перед и:: перед псевдоэлементом

Другим трюком является использование псевдоэлементов 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

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

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

Ответ 3

CSS

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

div:: after {
content: ";
background: url (image.jpg);
opacity: 0.5;
top: 0;
left: 0;
right: 0;
позиция: абсолютная;
z-index: -1;
}

HTML

<div>
поместите свой контент div
</div>

 

Ответ 4

Это можно сделать, используя другой класс div для текста Hi There...

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

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

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

Ответ 5

Я внедрил решение Marcus Ekwall, но смог удалить несколько вещей, чтобы сделать его более простым, и он все еще работает. Может быть, версия 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 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/

Ответ 6

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

	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> 

Ответ 7

<!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%)

Ответ 8

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