Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

html - Styling the same SVG <object> different ways

I want to have a series of the same SVG file on a page with different colours. I'm aware that the best method of getting the SVG into the page without bloating the code, and still have it externally stylable, is through the <object> tag.

Here's what I have so far:

HTML

<object type="image/svg+xml" data="images/circle.svg" class="object-circle red" >
    <!-- fallback image in CSS -->
</object>

<object type="image/svg+xml" data="images/circle.svg" class="object-circle blue" >
    <!-- fallback image in CSS -->
</object>

CSS

.object-circle {
    height:16px;
    width:16px;
}

.red .svg-circle {
    fill:#f00;
}
.blue .svg-circle {
    fill:#00f;
}

SVG

<?xml-stylesheet type="text/css" href="styles.css" ?>
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400" viewBox="0 0 400 400">
  <defs>
    <style>
      .svg-circle {
        fill-rule: evenodd;
      }
    </style>
  </defs>
  <path class="svg-circle" d="M200,398.688A199.552,199. ..."/>
</svg>

This just doesn't work as is. I believe there's an issue with targeting the <object> tag to manipulate the SVG's fill property in the CSS.

Taking the .red selector off the style sheet and leaving the .svg-circle selector in place works as expected - turning the circle red, but I want to be able to have several on the page with different colours.

Any help much appreciated!

If I can't crack this I might just resort to an old-fashioned .png sprite sheet.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

See https://css-tricks.com/using-svg/, section “Using SVG as an <object>”:

[…] if you want the CSS stuff to work, you can't use an external stylesheet or <style> on the document, you need to use a <style> element inside the SVG file itself.

So it seems that it is not possible to style SVG elements inside an object from “outside” the object via CSS.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...