Как изменить opacity background image

Как можно поменять прозрачность картинки через opacity заданной с помощью background-image не меняя при этом прозрачности всего остального содержимого div? К примеру: <div class="block" style="

Как можно поменять прозрачность картинки через opacity заданной с помощью background-image не меняя при этом прозрачности всего остального содержимого div?

К примеру:

<div class="block" style="background-image: pic.jpg;">
    <h1>Текст</h1>
</div>

Меняя opacity класса «block» естественно будет меняться opacity и заголовка в том числе, но нужно только background-image

задан 21 мая 2018 в 14:02

FWO's user avatar

FWOFWO

751 золотой знак3 серебряных знака11 бронзовых знаков

1

Такого свойства как background-opacity нет, но есть такая альтернатива: можно заменить background псевдоэлементом, и применить opacity уже к нему.

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

div::after {
  content: "";
  background: url(http://calculate-this.com/sites/default/files/styles/large/public/field/image/cat-3-icon.png?itok=w4QTmWF4);
  opacity: 0.5;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  position: absolute;
  z-index: -1;   
}
<div></div>

ответ дан 21 мая 2018 в 14:20

Rinat's user avatar

RinatRinat

863 бронзовых знака

Псевдоэлемент

.block {
  width:300px;
  height: 200px;
  position: relative;
    background:url(http://on-desktop.com/wps/Nature___Fields_Hilly_landscape_042589_.jpg);
}
.block2 {
  position: relative;
  left:40px;
  top:-140px;
    width:300px;
  height: 200px;
  z-index:1;
}
.block2::before {
  content:"";
  opacity: 0.5;
  position: absolute;
  z-index:-1;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background:url(http://on-desktop.com/wps/Nature___Fields_Hilly_landscape_042589_.jpg);
  background-size:cover;
}
<div class="block">
  foo bar
</div>
<div class="block2">
  baku reku
</div>

ответ дан 21 мая 2018 в 14:16

7

Если это просто какой-то цвет, то можно задать его с помощью rgba.

div {
  height: 200px;
  background: rgba(0, 0, 0, .2);
}
<div>
  text
</div>

А если картинка, то никак. Можно воспользоваться png фоном, либо сделать замену, когда нужно, например если экран стал маленький и нужно сделать фон прозрачным, то можно использовать media и просто подменить на картинку с нужной прозрачностью.

Хотя думаю, что найдутся какие-нибудь костыльные варианты

ответ дан 21 мая 2018 в 14:13

uzi_no_uzi's user avatar

uzi_no_uziuzi_no_uzi

2,1862 золотых знака16 серебряных знаков42 бронзовых знака

2

К примеру, если фон из фото и надо его сделать прозрачным можно поступить этим способом

* {
  margin: 0;
  padding: 0;
}

.item {
  width: 100vw;
  height: 100vh;
  background: url(http://nevseoboi.com.ua/uploads/posts/2012-02/1328215556-496551-0031795_www.nevseoboi.com.ua.jpg);
  background-size: 0 0;
  position: relative;
  padding-top: 20px;
}

.item:before {
  content: "";
  display: block;
  width: inherit;
  height: inherit;
  position: absolute;
  top: 0;
  left: 0;
  background: inherit;
  background-size: cover;
  opacity: .4;
}

.item p {
  font-size: 2em;
  width: 90%;
  margin: 0 auto;
}
<div class="item">
  <p>
    Lorem ipsum dolor, sit amet consectetur adipisicing elit. Dolore veniam similique libero adipisci officia unde, est neque harum. Corrupti ut consequatur totam maiores eveniet amet doloremque voluptatibus nostrum eaque nam dignissimos recusandae fuga ab,
    deleniti quo eligendi, repellat ea fugiat nesciunt reiciendis. Hic deleniti praesentium maxime esse consequuntur ut nesciunt!
  </p>
</div>

ответ дан 21 мая 2018 в 14:18

Вопрос мог устареть, но вот еще решение — может кому пригодится.
Прозрачность картинки задать с помощью градиента.

background-image: linear-gradient(180deg,rgba(0,0,0,0.5),rgba(0,0,0,0.5)),url('path to image');

rgba можно подобрать самостоятельно с помощью любого конвертера цветов

ответ дан 15 окт 2020 в 8:27

Владимир's user avatar

20 ноября, 2021 12:06 пп
1 010 views
| Комментариев нет

Development

opacity – это свойство CSS, которое позволяет настраивать прозрачность элемента. По умолчанию для всех элементов оно имеет значение 1. Приближая это значение к 0, вы можете сделать элемент более прозрачным.

Обычный вариант применения свойства opacity – использование изображения как части фона. Регулировка прозрачности может улучшить читаемость текста или поможет добиться желаемого визуального эффекта. Однако имейте в виду: невозможно менять opacity элемента background-image, не затрагивая при этом его дочерние элементы.

В этом руководстве мы предлагаем два метода обхода этого ограничения для фоновых изображений.

Требования

Чтобы следовать этой статье, вам понадобятся навыки работы с такими вещами:

  • opacity.
  • position: relative иposition: absolute.
  • контекст наложения и z-index.
  • псевдоэлементы :before и :after.

Метод 1: Изображения и абсолютное позиционирование

Первый подход будет основан на двух элементах (как можно понять из названия). Один из них – «обертка», которая обеспечивает точку отсчета с помощью position: relative. Второй – это элемент img, который появляется за контентом с помощью position: absolute и контекста наложения.

Разметка, написанная с применением этого подхода, может выглядеть так:

<div class="demo-wrap">
  <img
    class="demo-bg"
    src="https://your-image"
    alt=""
  >
  <div class="demo-content">
    <h1>Hello World!</h1>
  </div>
</div>

Соответствующие CSS-стили будут выглядеть так:

.demo-wrap {
  overflow: hidden;
  position: relative;
}

.demo-bg {
  opacity: 0.6;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: auto;
}

.demo-content {
  position: relative;
}

В итоге текст «Hello World!» будет наложен поверх изображения.

Родительский demo-wrap <div> устанавливает блок, содержащий абсолютное позиционирование. Для demo-bg <img> установлено значение position: absolute и присвоено свойство opacity . Для demo-content <div> установлено значение position: relative. Из-за организации разметки он имеет более высокий контекст наложения, чем demo-bg. Также для более точного управления контекстом наложения можно использовать z-index.

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

Метод 2: Псевдоэлементы CSS

Второй подход основан на псевдоэлементах. Псевдоэлементы :before и :after можно использовать для большинства CSS элементов. Как правило, вы предоставляете значение content и используете его для добавления дополнительного текста в начале или в конце. Однако так вы также можете добавить пустую строку, а затем использовать псевдоэлементы для дизайна.

Вот пример разметки для этого подхода:

<div class="demo-wrap">
  <div class="demo-content">
    <h1>Hello World!</h1>
  </div>
</div>

А вот – ее сопутствующие стили:

.demo-wrap {
  position: relative;
}

.demo-wrap:before {
  content: ' ';
  display: block;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  opacity: 0.6;
  background-image: url('https://your-image');
  background-repeat: no-repeat;
  background-position: 50% 0;
  background-size: cover;
}

.demo-content {
  position: relative;
}

Эта разметка и стили выведут фразу «Hello World!» поверх изображения.

Родительский demo-wrap <div> устанавливает блок, содержащий абсолютное позиционирование. Псевдоэлементу :before присвоено position: absolute с небольшой прозрачностью. Он использует background-size: cover, чтобы занять все доступное пространство.

Преимущество этого подхода заключается в поддержке других свойств фона, таких как background-position, background-repeat и background-size. Его недостатком является использование одного из псевдоэлементов, который может конфликтовать с другими эффектами дизайна – например, с clearfix.

Заключение

В этой статье мы рассмотрели два метода обхода ограничения для непрозрачных фоновых изображений.

Читайте также: Основы оптимизации шрифтов в CSS

Tags: CSS

Opacity — and its opposite, transparency — can be used in website design to create contrast and reinforce a brand’s identity. For example, Bellavista Building Group’s homepage features a slightly transparent background image with text overlay. This design technique reflects their brand values, which include transparency as well as integrity and accountability.

Junior developer learning how to set opacity of background in CSS

Download Now: 25 HTML & CSS Hacks [Free Guide]

Bellavista Building Group website uses opacity to set text against a slightly transparent background image

Image Source

Like horizontal scrolling, web textures, and many other web design techniques, opacity and transparency are best used sparingly and intentionally. Below we’ll walk through how to control the opacity of different elements, including:

  • background
  • text
  • border
  • image
  • gradient
  • color

To set the opacity of a background, image, text, or other element, you can use the CSS opacity property. Values for this property range from 0 to 1. If you set the property to 0, the styled element will be completely transparent (ie. invisible). If you set the property to 1, the element will be completely opaque.

Let’s look at an example of the same div element that’s styled differently with the opacity property. The first div is set to be completely opaque. The last is set to be completely transparent, which is why you can’t see it. The divs in between are set to be varying degrees of translucent.

Six div elements side by side styled with the CSS opacity property to go from completely opaque to completely transparent

Here’s the code:

See the Pen How to Set Opacity in CSS by Christina Perricone (@hubspot) on CodePen.

Another way to set the opacity of an element is using RGBA color values. We’ll take a look at this method below.

CSS Background Opacity

You can use the CSS opacity property to make the background of an element more transparent (or less). But beware: The opacity property not only makes the styled element transparent — it also makes its child elements transparent.

In other words, if I style a div that contains text with the opacity property, then both the div and the text in the div will be transparent. That can make the text really difficult to read, as in the example below.

See the Pen Setting Background Opacity with the CSS Opacity Property by Christina Perricone (@hubspot) on CodePen.

If you’d like to set the opacity of an element without affecting its child elements, then you need to use the CSS shorthand background property and RGBA color values instead.

RGB color codes is one way you can change the text color or background color of a web page in CSS. There’s also HTML color names and hex color codes, among other color models. What’s unique about the RGB color model is that you can control the color of an element and the opacity of that color.

To do so, you simply add an “a” to the rgb() prefix and add four values inside the parentheses. The first three numbers represent the intensity of the respective primary color (red, blue, green) as an integer between 0 and 255. The fourth value — ranging from 0 to 1 — sets the transparency of the color. 0 is completely transparent and 1 is completely opaque.

Let’s re-write the example above using the background property and RGBA color code.

See the Pen Setting Background Opacity with RGBA Color Code by Christina Perricone (@hubspot) on CodePen.

To learn more about this and other color models, check out CSS Colors: What You Need to Know About HTML, Hex, RGB & HSL Color Values.

Text Opacity CSS

Setting the opacity of text in CSS is nearly identical to setting the opacity of the background of an element. You can set the opacity of an entire element — the background, text within the element, the border, and everything else — using the opacity property.

To set the opacity of text and only text, then you need to use the CSS color property and RGBA color values. Below, I’ll set a paragraph to be slightly transparent against a dark solid background color.

See the Pen Text Opacity CSS by Christina Perricone (@hubspot) on CodePen.

When adjusting the opacity of text, make sure you maintain a color contrast ratio so that all users — including those with disabilities related to vision — can see and read the text. The current Web Content Accessibility Guidelines (WCAG) require a ratio of 4.5:1 for normal text and a ratio of 3:1 for large text such as headings. Large text is defined as 18.66px and bold or larger, or 24px or larger. Large text is defined as at least 14 point bolded text or 18 point text.

For more information on color accessibility, check out How to Identify Web Accessible Colors for Products & Websites.

Border Opacity CSS

Setting the opacity of a border in CSS is like setting the opacity of text. If you’d like to specify the opacity of the border of an element and nothing else, then you need to use the CSS shorthand border property and RGBA color values.

Below, I’ll set the border of a div to be black and very transparent so it provides a shadow effect.

See the Pen BaWwYVw by Christina Perricone (@hubspot) on CodePen.

Image Opacity in CSS

You can set the opacity of an image in CSS as well. The opacity property is frequently used with the :hover selector to style an image. That way, the opacity of the image will change only when a user hovers over it. You have two options.

You can have the image become transparent when the user hovers over it and then become opaque when their mouse moves away. That’s called a transparent hover effect. Or, you can set it so the image is somewhat transparent and then becomes opaque when the user hovers over it. That’s called a reverse transparent hover effect.

In the example below, you’ll see three images. One is set to be 40% see-through, no matter whether a user is hovering over it or not. One is set to be 40% transparent only when the user hovers over it. One is set to be 40% see-through and then change to 100% opaque when the user hovers over it.

See the Pen CSS Image Opacity [With Examples On Hover] by Christina Perricone (@hubspot) on CodePen.

You can also combine the opacity property with the animation or transition property to create a fade-in image transition in CSS.

CSS Opacity Gradient

In CSS, you can create a color gradient that shows one color gradually changing into another in a certain direction like top to bottom, left to right, or diagonally. Rather than changing from one color to a different color (think: red to blue), a gradient could show one color gradually changing from fully opaque to fully transparent.

To create this type of gradient, you can’t use the CSS opacity property. Instead, you’d use the background property and RGBA color values. The process is similar to changing background opacity but instead of defining the background property with one set of RGBA color values, you’ll set the property to “linear-gradient.” Then specify the direction of the gradient and at least two color stops in parentheses. Below is an example.

See the Pen bGqoLmL by Christina Perricone (@hubspot) on CodePen.

CSS Color Opacity

We have already looked at several ways to change the opacity of color in CSS. We have focused primarily on the opacity property and RGBA color model. However, there is another way to control the opacity of color in CSS: HSL colors.

HSLA is a color system that allows you to specify the hue, saturation, and lightness as well as the transparency of color.

HSLA is formatted similarly to RGBA color codes. It is composed of three numbers separated by commas. These numbers are then wrapped in parentheses and preceded by a lowercase “hsl.” You can add an “a” to “hsl” and a fourth value between 0 and 1 to set the transparency of the color.

While the first three numbers of RGB color codes represent the intensity of the respective primary color, the first three numbers of HSL color codes represent Hue, Saturation, and Lightness. Hue is measured in degrees on a scale of 0 – 360. Setting hue to 0 or 360 is red, 120 is green, 240 is blue. Saturation and Lightness are measured in percentages on a scale of 0 – 100. Saturation set to 0% is a shade of gray and 100% is the full color. Lightness set to 0% is black and 100% is white.

In the example below, I set the color of one div but don’t add an alpha parameter. As a result, it’s fully opaque by default. I set the color and opacity of the other div so it’s 50% see-through.

See the Pen Setting CSS Color Opacity with HSL Colors by Christina Perricone (@hubspot) on CodePen.

Notice that the text contained within the div is not affected so it is easy to read. That’s why you can change out the RGBA values used in any of the examples above for the respective HSLA values and achieve the same result.

Coding Transparency

If you want to create contrast and make text pop on your website, then you can use the CSS opacity property — or RGBA or HSLA color values —  to control the opacity of different elements on the page. You’ll just need to be familiar with some HTML and CSS.

coding templates

Понравилась статья? Поделить с друзьями:
  • Как изменить onclick через javascript
  • Как изменить ods на xls
  • Как изменить ns сервера reg ru
  • Как изменить ns записи wix
  • Как изменить npc sims 4