Search code examples
cssborderlinear-gradientsborder-image

How to implement two different linear gradient borders to an element?


I really new in CSS, and I have a task to create 2 linear-gradient as a border of a div like in the below image.

I used border-image for the inside one but I don't know how to create the other border.

border-image: linear-gradient(#EEEEEE ,#666666, #EEEEEE) 1 1% !important;

please see the attached picture.


Solution

  • Using an extra pseudo-element:

    I don't think it is possible to do this with just one element (that is, no extra pseudo/real elements) using border-image but you can do it using a pseudo-element by setting one border on the parent and the other on the pseudo-element like in the below snippet.

    div{
      position: relative;
      height: 200px;
      width: 400px;
      border-image-source: linear-gradient(to bottom, #FFFFFF, #CCCCCC 50%, #FFFFFF);
      border-style: solid;
      border-width: 5px;
      border-image-slice: 1;
    }
    div:before{
      position: absolute;
      content: '';
      height: calc(100% - 10px);
      width: calc(100% - 10px);
      border-image-source: linear-gradient(to bottom, #EEEEEE, #666666 50%, #EEEEEE);
      border-style: solid;
      border-width: 5px;
      border-image-slice: 1;
    }
    <div></div>


    Using a single element:

    With just a single element (no pseudo/real elements), we can sort of achieve this* using background-image but not with border-image. It is a lot more complex because we have to create a gradient strip for each of the 8 (4 outer + 4 inner) borders and then place them accordingly.

    * - This doesn't produce the exact same output as border-image but is close enough.

    div{
      height: 200px;
      width: 400px;
      background: linear-gradient(to right, #FFFFFF, #FFFFFF),
        linear-gradient(to bottom, #FFFFFF, #CCCCCC 50%, #FFFFFF),
        linear-gradient(to right, #FFFFFF, #FFFFFF),
        linear-gradient(to bottom, #FFFFFF, #CCCCCC 50%, #FFFFFF),
        linear-gradient(to right, #EEEEEE, #EEEEEE),
        linear-gradient(to bottom, #EEEEEE, #666666 50%, #EEEEEE),
        linear-gradient(to right, #EEEEEE, #EEEEEE),
        linear-gradient(to bottom, #EEEEEE, #666666 50%, #EEEEEE);
      background-repeat: no-repeat;
      background-size: 100% 5px, 5px 100%, 100% 5px, 5px 100%, calc(100% - 10px) 5px, 5px calc(100% - 10px), calc(100% - 10px) 5px, 5px calc(100% - 10px);
      background-position: 0px 0px, 100% 0px, 0px 100%, 0px 0px, 5px 5px, calc(100% - 5px), 0px calc(100% - 5px), 5px 5px;
    }
    <div></div>