How to overlay image with color in CSS?

前端 未结 11 824
轻奢々
轻奢々 2020-12-14 13:51

Objective

I want a color overlay on this header element. How can I do this with CSS?

Code

HTML

11条回答
  •  余生分开走
    2020-12-14 14:42

    If you want to just add a class to add the overlay:

    span {
      padding: 5px;
    }
    
    .green {
      background-color: green;
      color: #FFF;
    }
    
    .overlayed {
      position: relative;
    }
    
    .overlayed::before {
      content: ' ';
      z-index: 1;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background-color: #00000080;
    }
    
    .stand-out {
      position: relative;
      z-index: 2;
    }
    with overlay
    without overlay
    

    I stand out

    Important: the element you put the overlayed class on needs to have a position set. If it doesn't, the ::before element will take the size of some other parent element. In my example I've set the position to "relative" via the .overlayed rule, but in your use case you might need "absolute" or some other value.

    Also, make sure that the z-index of the overlayed class is higher than the ones of the eventual child elements of the container, unless you actually want for those to "stand out" and not be overlayed (as with the span with the stand-out class, in my snippet).

提交回复
热议问题