Search code examples
cssdropshadow

CSS3 Drop Shadow that's pushed in on both sides below the element


I'm trying to create the drop shadow effect like what's in the attached image.

The shadow with the code below appears directly beneath the element, but I need it to start about 20px from the left and 5px from the right.

Anybody have any tips on how to create this drop shadow offset on both sides?

drop shadow effect

.myDiv {
  width: 100px;
  height: 100px;
  box-shadow: 10px 0px 5px -2px #999;
}

Solution

  • Building on @Ghost Echo's answer this can be done responsively using the ::after pseudo element.

    Giving the pseudo element block display results in the element having 100% width of the relative parent, so simply adding a height:100% makes the element match the parent completely. Then it was just a case of adding a margin to shrink the ::after to the required width. The relative positioning and z-index are used to move the element behind the main <div> and the example box-shadow values are a close match to the image in question. You will probably need to change these to suit your exact requirements and also add a cross-browser box-shadow if needed.

    See demo or code below.

    CSS

    .myDiv {
        width: 100px;
        height: 100px;
        background-color:#fff;
        border:1px solid #eee; /* added for demo */
        position:relative;
    }
    .myDiv::after {
        content:"";
        display:block;
        margin:0 5px 0 20px;
        position:relative;
        z-index:-1;
        height:100%;
        box-shadow: 0 5px 5px 0 rgba(153, 153, 153, 1);
    }
    

    HTML

    <div class="myDiv"></div>
    

    If you need to support IE8 change ::after to :after as it only supports the old CSS2 syntax. There is no support for IE7 and below.