0

I'm new to svg. I've looked at w3schools, MDN, css-tricks and a bunch of youtube tuts. I'm stiil confused about using css with svg. Do I have to put the svg directly into the html? I would like to import the svg and still have the css work.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" href="test.css"> 

        <!-- css moved to external file test.css            
        <style>
            #down-glyph {
                fill: red;
            }
            #down-glyph:hover {
                fill: green;
            }
        </style>
        -->     
    </head>
    <body>

        <!-- svg copied from 'downbracket.svg'  this works -->
        <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 129 65'>
            <polygon id='down-glyph' fill="#e8e899" points=" 0.0,12.419 64.362,65.306 128.732,12.419 108.151,0.944 64.362,35.347 20.573,0.944"/>
        </svg>

        <!-- svg loads but styling not applied this way
        <object id='scroll-down' class='scroll-button' type="image/svg+xml" data="downbracket.svg">alternate here</object>
        -->

     </body>
 </html>

2 Answers 2

1

Here's a jsfiddle for you to test (note the use of the svg.js 0.x (latest) extension in the top left drop-down box): http://jsfiddle.net/Vac2Q/5531/

HTML:

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 129 65'>
  <polygon id='down-glyph' fill="#e8e899" points=" 0.0,12.419 64.362,65.306 128.732,12.419 108.151,0.944 64.362,35.347 20.573,0.944" />
</svg>

CSS:

#down-glyph {
    fill: red;
}
#down-glyph:hover {
   fill: green;
}

Yes, you can inline it within HTML, but you can also move it to a separate file. There are several ways to insert SVG and your way is fine for non-dynamic SVG. If the SVG is dynamic (interactive), learn the use of the <object> tag. If the SVG is static (no interaction), you can also import your SVG with the use of an<img src="image.svg" /> tag or with CSS like so:

#myelement {
    background-image: url(image.svg);
}
Sign up to request clarification or add additional context in comments.

Comments

0

I'm stiil confused about using css with svg. Do I have to put the svg directly into the html?

Yes.

CSS doesn't work across document boundaries. So if you have CSS in your HTML (or loaded by your HTML), that CSS will not apply to any SVG that is included from an external file (whether it be via <img>, <object> etc).

There is one workaround. You can use a script to load those external files and inline them in your HTML at runtime.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.