developer tip

임베디드 SVG에 스타일을 적용하는 방법은 무엇입니까?

copycodes 2020. 8. 15. 09:26
반응형

임베디드 SVG에 스타일을 적용하는 방법은 무엇입니까?


<svg>태그를 사용하여 SVG가 문서에 직접 포함되는 경우 문서의 스타일 시트를 통해 SVG에 CSS 스타일을 적용 할 수 있습니다. 그러나 <object>태그를 사용하여 포함 된 SVG에 스타일을 적용하려고합니다 .

다음 코드와 같은 것을 사용할 수 있습니까?

object svg { 
    fill: #fff; 
}

짧은 대답 : 아니요. 스타일은 문서 경계를 넘어 적용되지 않기 때문입니다.

그러나 <object>태그가 있으므로 스크립트를 사용하여 스타일 시트를 svg 문서에 삽입 할 수 있습니다.

다음과 같이이 코드는이 <object>완전히로드 되었다고 가정합니다 .

var svgDoc = yourObjectElement.contentDocument;
var styleElement = svgDoc.createElementNS("http://www.w3.org/2000/svg", "style");
styleElement.textContent = "svg { fill: #fff }"; // add whatever you need here
svgDoc.getElementById("where-to-insert").appendChild(styleElement);

<link>외부 스타일 시트를 참조하는 요소를 삽입 할 수도 있습니다 .

var svgDoc = yourObjectElement.contentDocument;
var linkElm = svgDoc.createElementNS("http://www.w3.org/1999/xhtml", "link");
linkElm.setAttribute("href", "my-style.css");
linkElm.setAttribute("type", "text/css");
linkElm.setAttribute("rel", "stylesheet");
svgDoc.getElementById("where-to-insert").appendChild(linkElm);

또 다른 옵션은 첫 번째 방법을 사용하여 스타일 요소를 삽입 한 다음 @import 규칙을 추가하는 것입니다 (예 : styleElement.textContent = "@import url(my-style.css)".

물론 스크립팅 없이도 svg 파일에서 스타일 시트에 직접 연결할 수 있습니다. 다음 중 하나가 작동합니다.

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="my-style.css" type="text/css"?>
<svg xmlns="http://www.w3.org/2000/svg">
  ... rest of document here ...
</svg>

또는:

<svg xmlns="http://www.w3.org/2000/svg">
  <defs>
    <link href="my-style.css" type="text/css" rel="stylesheet" 
          xmlns="http://www.w3.org/1999/xhtml"/>
  </defs>
  ... rest of document here ...
</svg>

업데이트 2015 : jquery-svg 플러그인을 사용 하여 포함 된 SVG에 js 스크립트 및 css 스타일을 적용 할 수 있습니다 .


SVG 파일 자체에 스타일이 포함 된 스타일 블록을 넣어 javsscrpt없이이를 수행 할 수 있습니다.

<style type="text/css">
 path,
 circle,
 polygon { 
    fill: #fff; 
  }
</style>

SVG를 포함하기 위해 태그를 사용하는 유일한 이유가 SVG의 마크 업으로 소스 코드를 복잡하게 만들고 싶지 않기 때문이라면 SVGInject 와 같은 SVG 인젝터를 살펴 봐야 합니다.

SVG injection uses Javascript to inject an SVG file inline into your HTML document. This allows for clean HTML source code while making the SVGs fully styleable with CSS. A basic example looks like this:

<html>
<head>
  <script src="svg-inject.min.js"></script>
</head>
<body>
  <img src="image.svg" onload="SVGInject(this)" />
</body>
</html>

참고URL : https://stackoverflow.com/questions/4906148/how-to-apply-a-style-to-an-embedded-svg

반응형