DEV Community

Cover image for CSS: Changing the opacity of the background-image only
Ruxin Qu
Ruxin Qu

Posted on • Updated on

CSS: Changing the opacity of the background-image only

  • Add a opaque background
body::before{
  content: " ";
  background-image: url();
  background-size: cover;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  opacity: 0.5;}
Enter fullscreen mode Exit fullscreen mode
  • Adding text on top of the opaque image HTML:
<body>
    <div class="overlay">
        <div class="header">
            <h1>Hello World</h1>
        </div>
    </div>
</body>

Enter fullscreen mode Exit fullscreen mode

CSS:

body {
    margin: 0;
}

.header {
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    background-image: url('https://lumiere-a.akamaihd.net/v1/images/sa_pixar_virtualbg_coco_16x9_9ccd7110.jpeg');
    background-position: center;
    height: 450px;
    width: 90%;
    margin: 0 auto;
}

.overlay::before {
    content: '';
    display: block;
    position: absolute;
    z-index: 1;
    height: 450px;
    width: 90%;
    left: 5%;
    background: rgb(0, 0, 0, 0.6);
}

.overlay * {
    position: relative;
}

h1 {
    color: #fff;
    z-index: 2;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)