How can one create an overlay in css?

前端 未结 9 2042
青春惊慌失措
青春惊慌失措 2020-11-29 17:58

I\'d like to create a div with an arbitrary size, then display something on top of that div. What is the best way to position and size the overlay exactly as the div below i

9条回答
  •  北海茫月
    2020-11-29 18:31

    If you don't mind messing with z-index, but you want to avoid adding extra div for overlay, you can use the following approach

    /* make sure ::before is positioned relative to .foo */
    .foo { position: relative; }
    
    /* overlay */
    .foo::before {
        content: '';
        display: block;
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.5);
        z-index: 0;
    }
    /* make sure all elements inside .foo placed above overlay element */
    .foo > * { z-index: 1; }
    

提交回复
热议问题