How to change only the background image opacity? [duplicate]

六眼飞鱼酱① 提交于 2019-12-24 08:04:11

问题


I am trying to change the opacity of my background image to make it match the website. The problem is that the opacity: 0.5; change everything within the element. So not only the background image change but also the text and every other element in the section. How am i supposed to change only the color of the image? Here is my code:

section {
   background-image: url(../IMG/Photo_NR1.jpg);
   padding: 15px;
   width: 100%;
   height: 700px;
}

I have done some research but i couldn't find anything. I tried to have all my elements out of the <section> tag but then i was forced to change the position of the elements again. Thanks for your time :)


回答1:


You could also do this by a pseudo element. Something like this:

section {
   position: relative;
   padding: 15px;
   width: 100%;
   height: 700px;
}

section::before {
  content: "";
  position: absolute;
  top: 0; 
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  opacity: .5; 
  background-image: url(../IMG/Photo_NR1.jpg);
}

So you do not need an image tag and you separating the design from content.




回答2:


Try to seperate the image.

Html:

<div class="my-container">
    <img src="your/image">
</div>

Css:

.my-container {
    position: relative;
    overflow: hidden;
}
.my-container img {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: auto;
    opacity: 0.5;
}

Source: https://scotch.io/tutorials/how-to-change-a-css-background-images-opacity



来源:https://stackoverflow.com/questions/49560988/how-to-change-only-the-background-image-opacity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!