Search code examples
csssvgviewbox

How to visually identify the viewbox of a SVG with CSS?


I'm willing to visually identify the viewbox of a SVG in order to avoid any element going out of it.

This is what I felt was the most intuitive way to do it in CSS (jsfiddle):

polygon{
    stroke:red;
    stroke-width:20px;
}

svg{
    stroke:blue;
    stroke-width:20px;
}

I was expecting the same behavior of the <svg> element than any other; i.e. I was expecting to have a 20px wide blue stroke around my <svg> element, as it's the case for my <polygon> element but my expectations were obviously over optimistic.

I'd like a direct interaction with CSS -- i.e., without having to programmatically create a <rect> element with the coordinates and positions of the viewbox.

Thanks for any help.


Solution

  • For the root svg you can simply use regular CSS styling, as opposed to stroke etc:

    Demo Fiddle

    Change

    svg{
        stroke:blue;
        stroke-width:20px;
    }
    

    To

    svg{
        border:20px solid blue;
    }