How to change the properties of a direct imported image in CSS?

1

Let's say you have defined an image as the background of a div as follows:

#div {
  background: #111111 url(../imagens/imagem1.jpg) top center;
  background-size: cover;

How do I change the properties of this image, for example:

filter: grayscale(100%);
opacity: 0.2;

Is it possible to make these changes only in the image? Because if you add those lines along with the other part code, the changes will be made across the Div, and that's not what I want.

    
asked by anonymous 29.05.2018 / 00:44

3 answers

1
For example, the image can be as BG does not have to be a ::after within the div

h1 {
    color: red;
}
div{
    width: 200px;
    height: 200px;
    position:relative
}
div::after {
    content: "";
    width: 100%;
    height: 100%;
    background-image: url(http://placecage.com/200/200);
    filter: grayscale(100%);
    opacity: 0.5;
    position:absolute;
    z-index:-1;
    top:0;
    left:0;
}
<div>
    <h1>Teste</h1>
</div>
    
29.05.2018 / 01:22
0

Properties filter and opacity are not applicable to background images, only to elements, such as div , for example. If you want a background image with opacity 0.2 , you would have to create a PNG with alpha by 20%.

But there is a gambiarra way you can emulate a background image by creating a layer with position absolute with a <img> element, so you can apply the properties of the element <img> independently of div .

Example:

#div{
   width: 300px;
   height: 200px;
   color: red;
   position: relative;
}

#div img{
   filter: grayscale(100%);
   opacity: 0.2;
   position: absolute;
   left: 0;
   width: 100%;
   z-index: -1;
}
<div id="div">
   <img src="https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg">
   <p>texto texto<p>
</div>
    
29.05.2018 / 01:25
0

You are assigning the properties of the 'div' with:

#div {
  background: #111111 url(../imagens/imagem1.jpg) top center;
  background-size: cover;
  filter: grayscale(100%);
  opacity: 0.2
}

To make the image independent of <div> use <img> within div instead of background: #111111 url(../imagens/imagem1.jpg) top center .

See:

<html>
    <head>
    <style>
    img {
        opacity: 0.5;
        filter: alpha(opacity=50); /* For IE8 and earlier */
    }
    
    img:hover {
        opacity: 1.0;
        filter: alpha(opacity=100); /* For IE8 and earlier */
    }
    div {
        background-color: black;
        opacity: 1.0;
        width:600px;
        height: 100px;
    }
    </style>
    </head>
    <h1>Image Transparency</h1>
    
    <div><img src="http://placecage.com/200/200"alt="nothing" width="170" height="100"></div>
    
    </body>
    </html>
    
29.05.2018 / 01:36