How to change the width of an svg rect with css

l00per picture l00per · Feb 28, 2014 · Viewed 10.4k times · Source

Is is possible to change width of SVG rectangle with CSS?

This doesn't work:

#red {
    width: 800px;
}
#red:hover {
    width: 1600px;
}

See jsfiddle.

Answer

Erik Dahlström picture Erik Dahlström · Feb 28, 2014

Since the width css property doesn't (yet) apply to <rect> elements you can't do it like in your question.

However, you can make it work by using units that depend on some other css property.

Like this, svg:

<rect id="red" width="1em" fill="red" height="270" />

and CSS:

#red {
    font-size: 800px;
}
#red:hover {
    font-size: 1600px;
}

See jsfiddle.

To answer the followup question, "how do you do this if you want to grow the height (or width) in the opposite direction?", here's one way:

Flip the coordinate system using transform="scale(1,-1)" (adjusting the other values to go along with that, e.g negative y coordinate position).

<rect id="red" y="-515.5" width="270" height="2em" transform="scale(1,-1)"/>

and CSS:

#red:hover {    
    animation: scaleheight 1s ease-in-out infinite alternate;
}

@keyframes scaleheight {
    0% {
         fill:red;
    }
    100% {
         fill:blue;
         font-size: 300px;
    }
}

See jsfiddle.