resizable box with rough edges using svg

Viewed 141

I am working on a small project where I need to build a a box with rough edges around text. For this I use an SVG with funky edges - sort of a bit like this one: https://ikedabarry.com/InkTex/wp-content/uploads/2012/07/Ink_039_6501.jpg (but as SVG).

What I am trying to achieve is that I add this as background to a DIV and that it always fills nicely to the edges of the containing DIV, on all sides, so that the DIV does NOT look perfectly square on any sides. No matter the size of the box (it resizes with screen-size).

This does not work right now.

What we use at the moment:

background-image: url(above.svg);
background-size: cover;

This does not work because only half the edges are rough as the other ones extend outside of the visible area.

We also tried:

background-size: 100% 100%;

but that does not work because I end up having the image following its own naturally size.

I am now not sure what is the best possible solution using JS / CSS to make this work.

Here is what I see as options:

OPTION 1: write some JS that:

a. listens to size changes in DIV

b. adds width and height to SVG

c. sets background image as 100% 100%.

OPTION 2:

a. add image as normal image with DIV

b. set DIV as position relative and IMAGE as position absolute

c. set top / bottom / left / right for image as ZERO. (it does not work right now because it is an SVG - not sure why).

I feel option 2 is the best, but I am wondering if I am overlooking something ...

Any help appreciated.

UPDATE: here is a runnable example: https://jsfiddle.net/sunnsideup/er1xd0wg/15/

2 Answers

Maybe try this:

background-size: 100vw 100vh;

I am not sure, if this is solution for your problem, but it can help

Here is what we have come up with:

https://jsfiddle.net/sunnsideup/er1xd0wg/15/

  1. create different SVGs for portrait / landscape divs so you dont end up with BG images that look straight because they are overstretched.

  2. remove height and width from svg, add viewbox like this with actual width and height:

viewBox="0 0 WIDTH HEIGHT"
  1. add to svg:
preserveAspectRatio="none"
  1. convert SVG to css background: https://yoksel.github.io/url-encoder/

  2. add the following css:

  background-image: url("data:image/svg+xml,.... SVG GOES HERE ...  ");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-position: center;
Related