How can I change a background image opacity without changing on div content? [duplicate]

StackOverflow https://stackoverflow.com/questions/23254346

  •  08-07-2023
  •  | 
  •  

سؤال

I want know that "How can I change background image opacity without changing on div content?"

I searched too much & I don't find a good answer to solve this issue!

HTML

<div class="div-1">
    <h2>title</h2>
    <p>text</p></div>

CSS

.div{
position:relative;
width:200px;
height:200px;
float:left;
color:white;
background:#7a8586 url('url') no-repeat local right;
overflow:hidden;
text-align: justify;
font-family:arial;
font-size:14px;}
هل كانت مفيدة؟

المحلول 2

Because all children of an element are affected by its CSS, you cannot simply set the opacity of a background-image, however, there are several workarounds to this:

1. Use transparent background images (easiest imo)

Rather than setting the background image's opacity after the fact, just make the background image transparent in your favorite image editor (try gimp, it's free!) and save it as an image with transparency (like PNG).

2. Use positioning.

If you make the parent element have relative positioning and absolutely position child elements inside, you take them out of the flow and they will not be affected by the opacity of the parent. [Source]

3. Use sibling elements in the same position

If you separate the content from the parent and make the two elements siblings, you can position the elements that were children over the parent with z-indexing and set the opacity of the parent without affecting the child.


There are more, but one of those should get you what you want.

نصائح أخرى

DEMO

You can use after or before pseudo element for background-image.

Css:

.has-bg-img{
    position: relative;
}
.has-bg-img:after {
    content:'';
    background: url('http://placehold.it/500x100') no-repeat center center;
    position: absolute;
    top:0px;
    left: 0px;
    width:100%;
    height:100%;
    z-index:-1;
    opacity: 0.2; /* Here is your opacity */
}

There is no CSS property background-opacity, but you can fake it by inserting a pseudo element with regular opacity the exact size of the element behind it.

check how is done http://css-tricks.com/snippets/css/transparent-background-images/

You can try this.....

 <div style="position:relative; ">      
      <div style=" background-image:url(url); opacity:0.5;filter:alpha(opacity=40);height:520px; width:520px;"></div>

       <div style="position:absolute; top:10px; z-index:100;left:10px;height:500px;idth:500px;">
            Your Div Contents are  Here..................
       </div>
    </div>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top