Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the width of an svg rect with css

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

This doesn't work:

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

See jsfiddle.

like image 726
l00per Avatar asked Dec 15 '22 01:12

l00per


1 Answers

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.

like image 106
Erik Dahlström Avatar answered Jan 01 '23 05:01

Erik Dahlström