user1763510
user1763510

Reputation: 1260

Truncated or partial borders with CSS

I am trying to do something like the picture below. I would like a div with 3 borders, but the outer 2 borders are truncated in the way displayed in the picture. I am wondering if it is possible to get this effect with a pure CSS solution:enter image description here

Upvotes: 0

Views: 1223

Answers (2)

Temani Afif
Temani Afif

Reputation: 272909

Here is a one element easy solution:

.box {
  width:200px;
  height:150px;
  margin:80px;
  border:10px solid red;
  position:relative;
}
.box:before,
.box:after {
  content:"";
  position:absolute;
  inset:-30px;
  border:10px solid #0000;
  border-image:linear-gradient(-45deg,blue 20%,#0000 0 80%,blue 0) 10;
}

.box:after {
  inset:-50px;
  border-image:linear-gradient(-45deg,green 20%,#0000 0 80%,green 0) 10;
}
<div class="box"></div>

Upvotes: 2

user1763510
user1763510

Reputation: 1260

Not sure if it is the simplest solution, but looks like I was able to do it with a background linear-gradient. Border colors help show the different components of the linear-gradient. Example here: https://jsfiddle.net/pn6a8rqj/171/

*{
  --bw:15px;
}


.corners>div{
  position:absolute;
}

.corners>div:nth-child(1),.corners>div:nth-child(2) {
  position:absolute;
  background:
    /*top left*/
    linear-gradient(to right, red var(--bw), transparent 0px) 0 0,    
    linear-gradient(135deg, blue calc(.7071*var(--bw)), transparent 0px) 0 var(--ch),
    linear-gradient(to bottom, green var(--bw), transparent 0) 0 0,
    linear-gradient(135deg, orange calc(.7071*var(--bw)), transparent 0px) var(--cw) 0,

    /*bottom right*/
    linear-gradient(to left, red var(--bw), transparent 0) 100% 100%,
    linear-gradient(315deg, blue calc(.7071*var(--bw)), transparent 0px) 100% calc(100% - var(--ch)),
    linear-gradient(to top, green var(--bw), transparent 0) 100% 100%,
    linear-gradient(315deg, orange calc(.7071*var(--bw)), transparent 0px) calc(100% - var(--cw)) 100%;

  background-repeat: no-repeat;
  background-size: var(--cw) var(--ch);
}

.corners>div:nth-child(1){
  top:0;
  left:0;
  --ch:var(--corner1Height);
  --cw:var(--corner1Width);
  width: calc(var(--width) + 8*var(--bw));
  height: calc(var(--height) + 8*var(--bw));
}
.corners>div:nth-child(2){
  top:calc(2*var(--bw));
  left:calc(2*var(--bw));
  --ch:var(--corner2Height);
  --cw:var(--corner2Width);
  width: calc(var(--width) + 4*var(--bw));
  height: calc(var(--height) + 4*var(--bw));
}

.corners>div:nth-child(3){
  box-sizing:border-box;
  top:calc(4*var(--bw));
  left:calc(4*var(--bw));
  border: var(--bw) solid black;
  width: var(--width);
  height: var(--height);
}


#div1 {
  --corner1Height:50px;
  --corner1Width:100px;
  --corner2Height:100px;
  --corner2Width:200px;
  --width:500px;
  --height:300px;
  width: var(--width);
  height: var(--height);
}

Upvotes: 1

Related Questions