Search code examples
htmlcssborderlinear-gradients

How can I create a dashed border with gradient?


enter image description here

I need to create a dashed border gradient like in this picture. Here's my CSS code.

.Rectangle-5 {
  margin: 51px 0px 0px 35px;
  display: inline-block;
  width: 370px;
  height: 280px;
  border-radius: 3px;
  border: 1px dashed;
  border-image-source: linear-gradient(to bottom, #4fc3f7, #ab5ca4 49%, #ff512f);
  border-image-slice: 1;
}

Solution

  • New answer

    Here is an improvement version of the initial answer with less of code. The idea is to rely on multiple background and adjust background-clip of each one.

    .container {
      display:inline-block;
      height: 200px;
      width: 200px;
      margin: 20px;
      border-radius:3px;
      border: 2px dotted #fff;
      background:
       linear-gradient(#fff 0 0) padding-box,
       linear-gradient(to bottom, #4fc3f7, #ab5ca4 49%, #ff512f) border-box; 
    }
    .alt {
      border: 2px dashed #fff;
    }
    <div class="container">
    
    </div>
    
    <div class="container alt">
    
    </div>



    Old answer

    You can apply linear-gradient as a background to an extern container and then use dotted or dashed border on inner container. As per your needs you have to use the white as color for the border and also as the background of the content like this :

    .container {
      display:inline-block;
      height: 200px;
      width: 200px;
      margin: 20px;
      background-image: linear-gradient(to bottom, #4fc3f7, #ab5ca4 49%, #ff512f);
    }
    
    .inner {
      border: 2px dotted #fff;
      height: calc(100% - 4px);
    }
    .inner-alt {
      border: 2px dashed #fff;
      height: calc(100% - 4px);
    }
    
    .content {
      background: #fff;
      height: 100%;
    }
    <div class="container">
      <div class="inner">
        <div class="content"></div>
      </div>
    </div>
    
    <div class="container">
      <div class="inner-alt">
        <div class="content"></div>
      </div>
    </div>

    You need to pay attention to the height of the inner container. It should be 100% but don't forget the border in calculation, that's why i used calc(100% - 4px) (2px for top border and 2px for bottom border).

    So if you change border height value you need also to update the height accordingly.