如何在不干扰覆盖文本的不透明度的情况下更改css中图像的不透明度

时间:2022-06-17 19:57:01

I want to change the opacity of an image in html but don't want to change the opacity of the text that is overwritten on it.

我想在html中更改图像的不透明度,但不想更改覆盖在其上的文本的不透明度。

this is my html code:-

这是我的HTML代码: -

<div class="image">
<img src = "C:/Users/Anmol/Desktop/NewSite/Images/background/bg_4.jpg">
<div class="text">
<h1>My Site</h1>
</div>
</div>

and this is its css code:-

这是它的css代码: -

.image{
       opacity: 0.5;
       margin: 0px 0px 0px 0px
       }
 .image .text {
               position:absolute;
               text-align: center;
               top:10px;
               right:500px;
               width:300px;
               }

Please tell me how could I do it(if possible)?

请告诉我怎么办(如果可能的话)?

2 个解决方案

#1


No, you can't do it directly, a child element can't have an opacity greater than the one of its parent.

不,你不能直接这样做,子元素的不透明度不能大于其父元素。

The easiest solution in your case is to not make the text a child of the image (have the image and the text at the same level for example):

在您的情况下,最简单的解决方案是不要使文本成为图像的子项(例如,将图像和文本放在同一级别):

.holder {
   position: relative;
}
.image{
   opacity: 0.5;
   margin: 0px 0px 0px 0px
}
.text {
  position:absolute;
  text-align: center;
  top:10px;
  width:300px;
}
<div class=holder>
  <div class="image">
    <img src = "http://i.imgur.com/IQRCO5Lm.jpg">
  </div>
  <div class="text">
    <h1>My Site</h1>
  </div>
</div>

#2


Instead of giving opacity to the parent div give opacity to the img itself. This way opacity will effect the image only leaving your text alone.

而不是给父div赋予不透明性给img本身不透明。这样,不透明度将影响图像,只留下文本。

img{ opacity: 0.5 }

#1


No, you can't do it directly, a child element can't have an opacity greater than the one of its parent.

不,你不能直接这样做,子元素的不透明度不能大于其父元素。

The easiest solution in your case is to not make the text a child of the image (have the image and the text at the same level for example):

在您的情况下,最简单的解决方案是不要使文本成为图像的子项(例如,将图像和文本放在同一级别):

.holder {
   position: relative;
}
.image{
   opacity: 0.5;
   margin: 0px 0px 0px 0px
}
.text {
  position:absolute;
  text-align: center;
  top:10px;
  width:300px;
}
<div class=holder>
  <div class="image">
    <img src = "http://i.imgur.com/IQRCO5Lm.jpg">
  </div>
  <div class="text">
    <h1>My Site</h1>
  </div>
</div>

#2


Instead of giving opacity to the parent div give opacity to the img itself. This way opacity will effect the image only leaving your text alone.

而不是给父div赋予不透明性给img本身不透明。这样,不透明度将影响图像,只留下文本。

img{ opacity: 0.5 }