Search code examples
cssbox-shadow

Add shadow to custom shape made with border in CSS


Ok, so in HTML I have one div tag with a before and after pseudo elements. This is my CSS:

.divClass{
    background: #41423D;
    height:30px;
}
.divClass:before{
    content: '';
    line-height: 0;
    font-size: 0;
    width: 0;
    height: 0;
    border-width :15px 7px 15px 7px;
    border-color: transparent #41423D #41423D transparent;
    border-style:solid;
    position: absolute;
    top: 0;
    left: -14px; 
}
.divClass:after{
    content: '';
    line-height: 0;
    font-size: 0;
    width: 0;
    height: 0;
    border-width :15px 7px 15px 7px;
    border-color: transparent transparent #41423D #41423D;
    border-style:solid;
    position: absolute;
    top: 0;
    right: -14px;
}

So, in design it becomes like this:

 ___ 
/   \

Now all I need is a shadow on the before and after pseudo elements which are the 2 triangles on either side of the div. The pseudo elements have 0 width and height so using box-shadow is a little tricky.

I need the shadow along the triangle. So, what can I do?


Solution

  • You can use unicode character : ▲ to make the triangles.

    Apply a text shadow on it.

    If the shape of the triangle is not what you want you can adjust it with transform: rotate(); or transform: skewX(); or both.

    It's a bit tricky and not perfect but it can works :

    span {
      display: inline-block;
      font-size: 70px;
      transform: skewX(29.5deg);
      color: red;
      text-shadow: 2px 2px 4px gray;
    }
    <span>▲</span>

    There are some other possibilities, all describe on a CSS Tricks post, so check it if you want :

    https://css-tricks.com/triangle-with-shadow/

    If think you can check filter: drop-shadow() too. In case you do not need a support for all the browsers it may works for you...

    edit:

    According to the css tricks post, can't you do that ?

    .triangle-with-shadow {
      transform: rotate(-45deg);
      width: 100px;
      height: 100px;
      position: relative;
      overflow: hidden;
      box-shadow: 0 20px 10px -17px rgba(0, 0, 0, 0.5);
    }
    .triangle-with-shadow:after {
      content: "";
      position: absolute;
      width: 50px;
      height: 50px;
      background: #999;
      transform: rotate(45deg); /* Prefixes... */
      top: 75px;
      left: 25px;
      box-shadow: -1px -1px 10px -2px rgba(0, 0, 0, 0.5);
    }
    <div class="triangle-with-shadow"></div>

    Another possibility if you just want the shape that you describe is to use the perspective :

    .shape {
      background: #41423D;
      width: 150px;
      height: 150px;
      margin: 20px auto;
      transform-origin:50% 100%;
      transform:perspective(100px) rotateX(30deg);
      box-shadow: 2px 2px 15px #41423D;
    }
    <div class="shape"></div>