Styling an element

The appearance of any tag inside an <svg> can be styled with the following attributes (the following are the attributes with example values):

  • fill=red or fill=#ff0000 will alter the color of the shape.
  • stroke=red or stroke=#ff0000 will alter stroke color. Stroke is a line that surrounds each element.
  • stroke-width=4 will adjust the width of the stroke.
  • fill-opacity=0.5 will adjust the transparency of the fill color.
  • stroke-opacity=0.5 will adjust the transparency of the stroke color.
  • transform = "translate(2,3)" will translate the element by the given xy values.
  • transform = "scale(2.1)" will scale the size of the element by the given proportion (for example, 2.1 times as big).
  • transform = "rotate(45)" will rotate the element by the given number of degrees.

Let's style the circle we positioned previously:

<circle r=50 cx=50 cy=50 fill=red stroke=blue stroke-width=5></circle>

Now we get this:

Note that the stroke in the preceding screenshot is getting clipped. That's because the stroke is created outside the element. If we want to see the full stroke, we can resize the circle:

<circle r=45 cx=50 cy=50 fill=red stroke=blue stroke-width=5></circle>

Now we get the following output:

Styling can also be done with CSS. The following steps will tell you how to style your <svg> element with CSS:

  1. Create an external app.css file in the same folder as your index.html file with the following contents:
      circle {
         fill:red;
         stroke:blue;
         stroke-width:3;
         fill-opacity:0.5;
         stroke-opacity:0.1;
         transform:rotate(45deg) scale(0.4) translate(155px, 
1px); r:50px; }
  1. Link the file in the <head> tag of index.html:
      <head> <link rel="stylesheet" href="app.css"> </head>
  1. Lastly, remove our previous inline styling that we had on our <circle> tag:
      <circle></circle>

Now we get this result:

Note that I've hovered over the element in the dev tools to show that the element has been rotated 45 degrees. That's what the blue box is.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.171.19