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


Tags: css,svg,viewbox

Problem :

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;
}

    CSS Howto..

    How to use SVG fragment identifier for CSS background image on iOS?

    how to unset max-height?

    How to define separate fonts for each font-style - CSS

    How to make list of all classes in the page using jQuery?

    How do I “smarten” my HTML/CSS tables so text fits to one line (cleverly)

    How to make width grow slowly when I add element?

    How to make a dropdown sub-menu expand to the right in Bootstrap 3

    How to make a bullet list align with text in css?

    Meteor how to serve multiple css for different media types?

    Show/Hide Div in jQuery, issue with “skipping” divs

    How to make a colorful gradient glow around your input-box?

    How come my