usernameabc
usernameabc

Reputation: 674

How to get lines around text with break in between?

I have to add lines around the text where there are spaces in between so that it is not just a matter of adding border all the way around. Below is what is expected, but I am not sure where to start to modify the border such that it has gaps like the image shows.

In terms of the spacing and border,

For the solution, if more html elements are needed or if we have to target any css pseudo elements, then that is fine.

Desired output:

border around text

I tried the following, but can't get it to work like the image.

.box { 
  border-top:    1px solid black;
  border-right:  1px solid black; 
  border-bottom: 1px solid black;
}
<div class="box">
Some text inside
</div>

Upvotes: 2

Views: 352

Answers (1)

Temani Afif
Temani Afif

Reputation: 272648

Use gradient

.box { 
  padding:20px;
  display:inline-block;
  border-right:2px solid;
  border-left:2px solid;
  background:
    linear-gradient(to left ,#000 10px,transparent 10px 30px,#000 0) top,
    linear-gradient(to right,#000 10px,transparent 10px 30px,#000 0) bottom;
  background-size:100% 2px;
  background-repeat:no-repeat;
}
<div class="box">
Some text inside
</div>

With CSS variable to make it easy to adjust:

.box { 
  --b:2px;  /* Thickness of border */
  --g:10px; /* The gap */
  --s:10px; /* The offset of the gap */
  
  --grad:#000 var(--s),transparent var(--s) calc(var(--s) + var(--g)),#000 0;
  padding:20px;
  display:inline-block;
  border-right:var(--b) solid;
  border-left:var(--b) solid;
  background:
    linear-gradient(to left ,var(--grad)) top,
    linear-gradient(to right,var(--grad)) bottom;
  background-size:100% var(--b);
  background-repeat:no-repeat;
}
<div class="box">
Some text inside
</div>

<div class="box" style="--s:20px;--g:50%;--b:5px;">
Some text 
</div>

<div class="box" style="--s:80%;--g:10%;--b:1px">
Some text<br> inside
</div>

Another idea using clip-path:

.box { 
  --b:2px;  /* Thickness of border */
  --g:10px; /* The gap */
  --s:10px; /* The offset of the gap */

  padding:20px;
  display:inline-block;
  border:var(--b) solid;
  clip-path:polygon(0 0, 
  
    calc(100% - var(--s) - var(--g)) 0,
    calc(100% - var(--s) - var(--g)) var(--b),
    calc(100% - var(--s))            var(--b),
    calc(100% - var(--s))            0,
  
    100% 0,100% 100%, 
    
    calc(var(--s) + var(--g)) 100%,
    calc(var(--s) + var(--g)) calc(100% - var(--b)),
    var(--s)                  calc(100% - var(--b)),
    var(--s)                  100%,
    
    0 100%);
}
<div class="box">
Some text inside
</div>

<div class="box" style="--s:20px;--g:50%;--b:5px;">
Some text 
</div>

<div class="box" style="--s:80%;--g:10%;--b:1px">
Some text<br> inside
</div>

Upvotes: 3

Related Questions