SVG, CSS and the ‘use’ element

SVG, CSS and the ‘use’ element

SVG, CSS y el elemento 'use'

In the post about Illustrator and SVG I already pointed out that the utility I saw in Illustrator to work with SVG was the creation of graphic elements and their gradients and colors. Now I want to use an illustration converted into SVG from Illustrator in order to manipulate it with CSS and verify the possibilities of the ‘use’ element. To do that, I have located Iberdrola’s logo in vector format and I have opened it in Illustrator to export it to SVG. I have selected this logo because it has several shapes and it uses several types of gradients.

I am going to reformat the code generated by Illustrator so that it is more comfortable to work.

  • I have removed the Illustrator comments
  • I have eliminated the ‘x’ and ‘y’ coordinates of the SVG label considering they have no effect on no nested SVG labels. I have also eliminated the ‘width’ and ‘height’ attributes of this label and, as I do not specify  any value in them, its value will be of 100%, which is what I want it to takes up in the iframe in which I will insert the SVG.
  • I have renamed the ‘class’ to give identical names to the ‘id’ I have used in Illustrator so that it will be easier to recognize each object which it amends.
  • I have placed on one side all the gradients and on the other side the groups and paths within a ‘symbol’ in order to leave the code more organized. I have put all inside a ‘def’ label. I have assigned a ‘viewbox’ attribute to the ‘symbol’ with the size of the logo and the preserveAspectRatio=”xMinYMin meet” attribute to rescale it keeping the dimensions and visibility of the whole logo when is instantiated with ‘use’.
  • I have used the ‘use’ label to show the logo, in such a way that I can reuse it as many times as I need.
  • I have leaved the ‘d’ attribute of the paths on the same line at the end of the attribute, since it’s a content which I am not going to use or manipulate and it is the one which occupies the most.

We can embed the SVG file in our page with the ‘iframe’,‘object’ and ‘img’ labels or directly in the HTML.

We already have better organized the code in the following SVG.

The ‘use’ label may seem an ideal solution to reuse elements and manipulate them with CSS, this way, by simply changing the ‘class’, it could show the same logo in color or in black and white, but it has to be taken into account that the DOM of the referenced element with the ‘use’ label does not stay exposed, so the different child elements of the referenced element cannot be modified with CSS. It is a pity, but we want to show the logo in color and in black and white, we will have to double its code.

What we really can do is to manipulate the different attributes of the ‘use’ label in order to change the referenced element or its size and position properties.

Tags:
©2019 PoseLab SL. All rights reserved.