Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do scale 9 with CSS or JS with a rectangle

I would like to have a custom CSS border texture around a rectangle, like hand-drawn cross-hatching for example. In theory I would create a "scale 9" slicing of the rectangle so no matter what dimensions it had it would always have the border.

enter image description here

Is anything like this possible purely in CSS? Or if not, then how could you accomplish this in JS? I am thinking in terms of creating a text input with an inner shadow sort of border effect around it using cross-hatching. Wondering if/how can that be done in pure CSS or if not pure CSS then in JS.

Side note, just discovered border-image, not sure if that's related.

I would like to have borders look essentially along the lines of this:

enter image description here

like image 931
Lance Avatar asked Mar 17 '26 19:03

Lance


1 Answers

I would use border-image for this.

#border-image {
  font-size: 20px;
  width:300px;
  border: 10px solid black;
  padding: 35px;
  margin: 2em;
  
  
  border-image-source: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22'  viewBox='0 0 22 22'%3E%3Cpath d='M2,5 Q2,2 5,2L17,2 Q20,2 20,5L20,17 Q20,20 17,20L5,20 Q2,20 2,17Z' stroke='red' fill='none' /%3E%3C/svg%3E");
  border-image-slice: 5;
  border-image-repeat: round;
  border-image-width: 22px;
}

}
<div id="border-image" class="bi">
</div>

For the border-image-source I'm using an SVG element:

<svg id="svg" viewBox='0 0 22 22' width='200'>
<path d='M2,5 Q2,2 5,2L17,2 Q20,2 20,5L20,17 Q20,20 17,20L5,20 Q2,20 2,17Z' stroke='red' fill='none'  />
</svg>

If you want to use this svg element as background you can encode it to this:

"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22'  viewBox='0 0 22 22'%3E%3Cpath d='M2,5 Q2,2 5,2L17,2 Q20,2 20,5L20,17 Q20,20 17,20L5,20 Q2,20 2,17Z' stroke='red' fill='none' /%3E%3C/svg%3E"

In order to encode the svg to data uri you can use this URL-encoder for SVG

The value I'm using for the border-image-slice is 5 since this is the size of the rounded corners.

Codrops border-image

In the previous image this would be the size of the C1, C2,C3 and C4 The image is from this article: border-image

See this in an example:

svg{border:1px solid}
line{stroke:black; stroke-width:.1}
<svg id="svg" viewBox='0 0 22 22' width='200'>
<path d='M2,5 Q2,2 5,2L17,2 Q20,2 20,5L20,17 Q20,20 17,20L5,20 Q2,20 2,17Z' stroke='red' fill='none'  />
  <g id="lines1">
  <line class="h" x1="0" x2="22" y1="5" y2="5"></line>
  <line class="h" x1="0" x2="22" y1="17" y2="17"></line>

  <line class="v" x1="5" x2="5" y1="0" y2="22"></line>
  <line class="v" x1="17" x2="17" y1="0" y2="22"></line>
</g>
</svg>

I'm using border-image-width: 22px; but of coarse you can change this:

Please read more about border-image

like image 78
enxaneta Avatar answered Mar 19 '26 10:03

enxaneta