DEV Community

jsnkuhn
jsnkuhn

Posted on

Recreating `border-image` with `background-image` for the curious

Since border-image was first introduced around 2010 to this day I've received one consistent comment from my fellow developers any time I use it:

Why not just use background-image instead?

So here it is folks! Here's the default border-image code versus what you'd have to do in background-image to get the same result. This is why I don't do that!

border: solid 27px;
border-image: url('border.png') 27; 
Enter fullscreen mode Exit fullscreen mode

Equivalent background image code:

/* don't do this */
background: 
  url('top-left-corner.png') 0 0 / 20px 20px no-repeat, 
  url('top-right-corner.png') 100% 0 / 20px 20px no-repeat,
  url('bottom-left-corner.png') 0 100% / 20px 20px no-repeat,
  url('bottom-right-corner.png') 100% 100% / 20px 20px no-repeat,
  url('left-border.png') 0 20px / 20px calc(100% - 40px) no-repeat,
  url('right-border.png') 100% 20px / 20px calc(100% - 40px) no-repeat,
  url('top-border.png') 20px 0 / calc(100% - 40px) 20px no-repeat,
  url('bottom-border.png') 20px 100% / calc(100% - 40px) 20px no-repeat;
Enter fullscreen mode Exit fullscreen mode

Top comments (6)

Collapse
 
abhinav1217 profile image
Abhinav Kulshreshtha

I don't any benefit of doing this? If you could provide a codepen or before-after screenshot of final output, maybe it could provide some context on why would someone choose to make 8 network calls for something which ideally shouldn't even need it.

Collapse
 
jsnkuhn profile image
jsnkuhn

Codepen is now included.

To be fair if the border-image-source begin used is symmetrical you might only need 3 network requests (one for left/right border, one for top/bottom border and one for the corners)... Or with an SVG fragment identifiers could be used on 1 single image. But yes it's still likely much more work then just using border-image proper.

Collapse
 
afif profile image
Temani Afif

why doing this? I wouldn't call this an equivalent because all depend on the the image you will be using

Collapse
 
jsnkuhn profile image
jsnkuhn

The point is to show the absurdity of people's constant reaction to use of border-image with "why not just use background"

Collapse
 
afif profile image
Temani Afif

there is no absurdity. Each method has its use cases and you are not demonstrating anything by using a generic code. Better give a real example with a real image if you want to highlight a fact or to compare between both method.

Both code provided aren't equivalent at all.

Collapse
 
jsnkuhn profile image
jsnkuhn

Post updated with Codepen example to show the equivalence and an extra explanation to hopefully clear up some confusion.