the code is just a simple:
&
You can use linear-gradient
and you only need one element:
.box {
margin:30px;
width:100px;
height:100px;
padding:10px;
background:
linear-gradient(#fff,#fff) 10px 0,
linear-gradient(#fff,#fff) 0 10px,
linear-gradient(#fff,#fff) calc(100% - 10px) 0,
linear-gradient(#fff,#fff) 0 calc(100% - 10px);
background-size:1px 100%,100% 1px;
background-repeat:no-repeat;
}
body {
background:green;
}
<div class="box">
</div>
You can also rely on CSS variable to easily control the intersection:
.box {
margin:20px;
width:100px;
height:100px;
padding:var(--c,10px);
background:
linear-gradient(#fff,#fff) var(--c,10px) 0,
linear-gradient(#fff,#fff) 0 var(--c,10px),
linear-gradient(#fff,#fff) calc(100% - var(--c,10px)) 0,
linear-gradient(#fff,#fff) 0 calc(100% - var(--c,10px));
background-size:1px 100%,100% 1px;
background-repeat:no-repeat;
display:inline-block;
box-sizing:border-box;
}
body {
background:green;
}
<div class="box">
</div>
<div class="box" style="--c:20px;">
</div>
<div class="box" style="--c:0px;">
</div>
<div class="box" style="--c:40px;">
</div>
Same logic with a different syntax:
.box {
margin:20px;
width:100px;
height:100px;
padding:var(--c,10px);
background:
linear-gradient(#fff,#fff) left,
linear-gradient(#fff,#fff) top,
linear-gradient(#fff,#fff) right,
linear-gradient(#fff,#fff) bottom;
background-size:1px 100vh,100vw 1px;
background-origin:content-box;
background-repeat:no-repeat;
display:inline-block;
box-sizing:border-box;
}
body {
background:green;
}
<div class="box">
</div>
<div class="box" style="--c:20px;">
</div>
<div class="box" style="--c:0px;">
</div>
<div class="box" style="--c:40px;">
</div>
If you can add ::before
and ::after
pseudo-elements to the inner div, you can have one generate the top and bottom borders and the other generate the left and right borders. Then offset them so that their borders start and end outside the area of the inner div. Not the most elegant solution as it requires the inner div to be positioned, but it works pretty well.
Note that the borders will extend outside of the inner div's area without causing it to be shifted away from its static position, which I'm assuming is the goal here. If you want the div to be constricted, give it positive margins equal to the offset of the borders (so borders with -2px offsets mean giving your inner div 2px margins).
body {
background: green;
}
.top {
width: 200px;
height: 200px;
}
.inner {
position: relative;
height: 100%; /* To simulate content */
}
.inner::before, .inner::after {
content: '';
position: absolute;
border: solid white;
}
.inner::before {
top: 0;
right: -2px;
bottom: 0;
left: -2px;
border-width: 1px 0;
}
.inner::after {
top: -2px;
right: 0;
bottom: -2px;
left: 0;
border-width: 0 1px;
}
<div class="top">
<div class="inner"></div>
</div>