5

Здравствуйте как подключить через CSS3 svg ?

3
  • background-image: url(picture.svg);
    – soledar10
    29 мар 2017 в 18:04
  • на css tricks говорили что надо подключать таким методом float: left; text-indent: -9999px; width: 18px; height: 18px; background: url(../img/briefcase-outline.svg); background-size: 18px;
    – brin gonor
    29 мар 2017 в 18:06
  • 2
    @bringonor, вот это все - float: left; text-indent: -9999px; width: 18px; height: 18px; для дополнительной стилизации. Основное тут - background: url(../img/briefcase-outline.svg);
    – SVE
    29 мар 2017 в 19:10

2 ответа 2

7

.logo {
/* Стили для наглядности */
  display: block;
  text-indent: -9999px;
  width: 300px;
  height: 200px; 
  
  background: url(http://s.cdpn.io/3/kiwi.svg); /* Подключение SVG */
  background-repeat: no-repeat;
  background-size: contain;
}
<a href="/" class="logo">
  Kiwi Corp
</a>

ресурс перевод


Вот просто блок с одним лишь svg на фоне:

div {
  background: url(https://tatica.fedorapeople.org/Themes/F12/wallpaper-mosaico6.svg); /* Подключение SVG */
  
}
<div>
   Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima pariatur rem recusandae porro itaque delectus esse voluptatibus, iusto consequuntur dolore?
   Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima pariatur rem recusandae porro itaque delectus esse voluptatibus, iusto consequuntur dolore?
   Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima pariatur rem recusandae porro itaque delectus esse voluptatibus, iusto consequuntur dolore?
   Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima pariatur rem recusandae porro itaque delectus esse voluptatibus, iusto consequuntur dolore?
   Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima pariatur rem recusandae porro itaque delectus esse voluptatibus, iusto consequuntur dolore?
</div>

6

Здравствуйте как подключить через CSS3 svg ?

Вопрос глобальный.
SVG и CSS очень тесно взаимодействуют друг с другом.

Стили CSS могут управлять элементами SVG, как из внешней таблицы стилей, так и могут быть размещены внутри файла *.svg

<svg id="svg" xmlns="http://www.w3.org/2000/svg" width="300" height="300" viewBox="0 0 300 300">
        <defs>
            <style>
                .cls-1{fill:#64b2c1;}
                .cls-2{fill:orange;}
                .cls-3{fill:transparent;stroke-miterlimit:10;}
                .cls-4{fill:#191919;}
            </style>
        </defs> 
<rect class="cls-1" width="100" height="100" />
<rect class="cls-2" x="100" y="100" width="100" height="100" />
</svg>  

Для подключения внешней таблицы стилей для кроссбраузерного решения в шапку файла SVG добавляется ещё одна строка.

<?xml-stylesheet href="mystyle.css" type="text/css"?>

При этом желательно чтобы файлы *.svg и *.css находились в одной папке.
Браузер chrome особенно чувствителен к этому.
Для добавления svg файла в html существует несколько способов - подробнее здесь Но если вы хотите использовать svg в полном объеме, то самый надежный метод для обеспечения интерактивности - это тег <object>

<object type="image/svg+xml" data="SvgImg.svg" width="200" height="200">
 <img src="SvgImg.png" width="200" height="200" alt="image format png" />
</object>

Браузер не понимающий SVG проигнорирует тег object и перейдет к следующему тегу img и обработает его, как обычный HTML тег и выведет картинку.

Ниже пример полного кода, показывающего интерактивность svg и управление через стили css. Поочередно наведите курсор на силуэты мужчины и женщины.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="225" height="250" version="1.1"
viewBox="0 0 255 250" preserveAspectRatio="none"
      xmlns="http://www.w3.org/2000/svg" >
  <title>animation marker</title>
   	<defs>
		<style type="text/css"><![CDATA[
			#man:hover {
				fill:green;
				opacity: 0.5;
							}
			#woman:hover{
			    fill:red;
				opacity: 0.5; 
					   }	 
				 ]]> </style>
    <pattern id="newpattern"
		 x="0" y="0" width="20" height="20"
		 patternUnits="userSpaceOnUse" >
    		   
		<g fill="#85D2FF" stroke-width="1px" stroke="none" fill-opacity="0.5">
			 <rect x="0" y="0" width="10" height="10" />
			 <rect x="10" y="10" width="10" height="10" />
		</g>
    </pattern>
     		
		<marker id="end-circle"   markerUnits="userSpaceOnUse"
			 markerWidth="40" markerHeight="40" refX="10"  refY="2" orient="auto">
			<rect x="0" y="0" width="40" height="20" 
			 stroke="black" fill="grey" fill-opacity="0.5"/>
				<circle cx="10" cy="10"  r="10" 
			    	style="fill:lime;  stroke-width:2px; stroke:tomato;" />
		</marker>
	
   </defs>
   <g >
      <!-- the filling pattern of the entire working area 	 -->
	 <rect x="0" y="0" width="100%" height="100%"
      style="stroke: #000000; fill: url(#newpattern);" />      
    
	<!-- tower mill -->
	<line x1="120" y1="250" x2="120" y="0" stroke="black" />
	
      <path d="M80,250 L80,100 L120,20 160,100 160,250 
            M80,100 L160,100" 
     		  fill="silver" stroke="black" />
        
	<!--window mill -->
	 <g stroke="silver">
	  <path d="M100,80 L110,60 L130,60 L140,80z" fill="yellow"  />
       <rect x="123"  y="150" width="36" height="30" stroke="grey" fill="yellow" />	 
	     <line x1="120" y1="250" x2="120" y2="100"  />
		  <line x1="120" y1="170" x2="160" y2="170"  />
		   <line x1="120" y1="160" x2="160" y2="160"  />
		    <line x1="110" y1="80" x2="110" y2="60"  />
			 <line x1="120" y1="80" x2="120" y2="60"  />
			  <line x1="130" y1="80" x2="130" y2="60"  />
	</g>
	 <!--  flag -->
	   <path d="M120,2 L140,2  L133,7 L140,12 L120,12z" stroke="orange" fill="crimson"  />
    <!-- stairs and curbs -->	
       <path d="M160,220 h10 v10 h10 v10 h10 v10 h-30z" fill="silver" stroke="black" />	
	     <line x1="80" y1="102" x2="160" y2="102" stroke-width="5px" stroke="slategray" stroke-dasharray="6,2" />
	        <line x1="80" y1="240" x2="160" y2="240" stroke-width="5px" stroke="slategray" stroke-dasharray="6,2" />
			  <line x1="85" y1="245" x2="160" y2="245" stroke-width="5px" stroke="slategray" stroke-dasharray="6,2" />
	   
    <!-- Four rotating marker blades of the windmill -->   
   <g style=" fill:none; stroke:green; stroke-width:4;  marker-end: url(#end-circle);">
	 <desc>the animation of the four markers </desc>
	 <line x1="120" y1="110" x2="120" y2="40"  	/>	  
	  <line x1="130" y1="120" x2="200" y2="120"  />
       <line x1="120" y1="130" x2="120" y2="200"  />	 
	    <line x1="110" y1="120" x2="40" y2="120"  	/>
	 <animateTransform attributeType="xml"
		  attributeName="transform"
		  type="rotate"
		  from="0 120 120"
		  to="360 120 120"
		  begin="man.mouseover"
		  end="woman.mouseover"
		  dur="2.5s"
		  repeatCount="indefinite" fill="freeze"/>
	<!-- the Central circles of the blades of the mill -->    
	   <circle cx="120" cy="120" r="10" fill="limegreen" stroke="green" />
	   <circle cx="120" cy="120" r="3" fill="green" />
   </g> 
  <!-- the control unit buton -"Start" -->
  <g transform="translate(135, 145)" >Start"> 
	   <g id="man" transform="translate(25 0)" fill="#ccf" stroke="black">
		<circle cx="85" cy="56" r="10"/>
		<line x1="85" y1="66" x2="85" y2="80"/>
		<polyline points="76 104, 85 80, 94 104" />
		 <polyline points="76 70, 85 76, 94 70" />
	   </g>	
        <!-- the control unit buton -"Stop" -->
	 <g id="woman" transform="translate(-25 0)" fill=" #ffffcc" stroke="black">
		 <circle cx="110" cy="56" r="10" />
		 <polyline points="110 66, 110 80, 100 90, 120 90, 110 80" />
		 <line x1="104" y1="104" x2="108" y2="90" />
		 <line x1="112" y1="90" x2="116" y2="104"/>
		 <line x1="112" y1="90" x2="116" y2="104"/>
	 </g>
 </g>	 
	 <g font-size="14" font-weight="bold" font-family="serif" text-anchor="middle" fill="crimson"  >
		<text  x="251" y="167"  transform="rotate(-90 251,167) translate(0,-25)" >Stop </text>
			<text  x="225" y="167"  transform="rotate(-90 225,167) translate(0,25)" >Start  </text>
	 </g>	
	 </g>
	 </svg>
    		   
		<g fill="#85D2FF" stroke-width="1px" stroke="none" fill-opacity="0.5">
			 <rect x="0" y="0" width="10" height="10" />
			 <rect x="10" y="10" width="10" height="10" />
		</g>
    </pattern>
     		
		<marker id="end-circle"   markerUnits="userSpaceOnUse"
			 markerWidth="40" markerHeight="40" refX="10"  refY="2" orient="auto">
			<rect x="0" y="0" width="40" height="20" 
			 stroke="black" fill="grey" fill-opacity="0.5"/>
				<circle cx="10" cy="10"  r="10" 
			    	style="fill:lime;  stroke-width:2px; stroke:tomato;" />
		</marker>
	
   </defs>
   <g >
      <!-- the filling pattern of the entire working area 	 -->
	 <rect x="0" y="0" width="100%" height="100%"
      style="stroke: #000000; fill: url(#newpattern);" />      
    
	<!-- tower mill -->
	<line x1="120" y1="250" x2="120" y="0" stroke="black" />
	
      <path d="M80,250 L80,100 L120,20 160,100 160,250 
            M80,100 L160,100" 
     		  fill="silver" stroke="black" />
        
	<!--window mill -->
	 <g stroke="silver">
	  <path d="M100,80 L110,60 L130,60 L140,80z" fill="yellow"  />
       <rect x="123"  y="150" width="36" height="30" stroke="grey" fill="yellow" />	 
	     <line x1="120" y1="250" x2="120" y2="100"  />
		  <line x1="120" y1="170" x2="160" y2="170"  />
		   <line x1="120" y1="160" x2="160" y2="160"  />
		    <line x1="110" y1="80" x2="110" y2="60"  />
			 <line x1="120" y1="80" x2="120" y2="60"  />
			  <line x1="130" y1="80" x2="130" y2="60"  />
	</g>
	 <!--  flag -->
	   <path d="M120,2 L140,2  L133,7 L140,12 L120,12z" stroke="orange" fill="crimson"  />
    <!-- stairs and curbs -->	
       <path d="M160,220 h10 v10 h10 v10 h10 v10 h-30z" fill="silver" stroke="black" />	
	     <line x1="80" y1="102" x2="160" y2="102" stroke-width="5px" stroke="slategray" stroke-dasharray="6,2" />
	        <line x1="80" y1="240" x2="160" y2="240" stroke-width="5px" stroke="slategray" stroke-dasharray="6,2" />
			  <line x1="85" y1="245" x2="160" y2="245" stroke-width="5px" stroke="slategray" stroke-dasharray="6,2" />
	   
    <!-- Four rotating marker blades of the windmill -->   
   <g style=" fill:none; stroke:green; stroke-width:4;  marker-end: url(#end-circle);">
	
	 <line x1="120" y1="110" x2="120" y2="40"  	/>	  
	  <line x1="130" y1="120" x2="200" y2="120"  />
       <line x1="120" y1="130" x2="120" y2="200"  />	 
	    <line x1="110" y1="120" x2="40" y2="120"  	/>
	 <animateTransform attributeType="xml"
		  attributeName="transform"
		  type="rotate"
		  from="0 120 120"
		  to="360 120 120"
		  begin="man.mouseover"
		  end="woman.mouseover"
		  dur="2.5s"
		  repeatCount="indefinite" fill="freeze"/>
	<!-- the Central circles of the blades of the mill -->    
	   <circle cx="120" cy="120" r="10" fill="limegreen" stroke="green" />
	   <circle cx="120" cy="120" r="3" fill="green" />
   </g> 
  <!-- the control unit buton -"Start" -->
  <g transform="translate(135, 145)" >Start"> 
	   <g id="man" transform="translate(25 0)" fill="#ccf" stroke="black">
		<circle cx="85" cy="56" r="10"/>
		<line x1="85" y1="66" x2="85" y2="80"/>
		<polyline points="76 104, 85 80, 94 104" />
		 <polyline points="76 70, 85 76, 94 70" />
	   </g>	
        <!-- the control unit buton -"Stop" -->
	 <g id="woman" transform="translate(-25 0)" fill=" #ffffcc" stroke="black">
		 <circle cx="110" cy="56" r="10" />
		 <polyline points="110 66, 110 80, 100 90, 120 90, 110 80" />
		 <line x1="104" y1="104" x2="108" y2="90" />
		 <line x1="112" y1="90" x2="116" y2="104"/>
		 <line x1="112" y1="90" x2="116" y2="104"/>
	 </g>
 </g>	 
	 <g font-size="14" font-weight="bold" font-family="serif" text-anchor="middle" fill="crimson"  >
		<text  x="251" y="167"  transform="rotate(-90 251,167) translate(0,-25)" >Stop </text>
			<text  x="225" y="167"  transform="rotate(-90 225,167) translate(0,25)" >Start  </text>
	 </g>	
	 </g>
	 </svg>

4
  • 1
    Подскажите, а инлайнить <clipPath> в CSS как-нибудь можно? Чтобы как-нибудь вот так: clip-path: url('data:image/svg+xml;utf8,<svg><clipPath></clipPath></svg>') 30 мар 2017 в 9:02
  • @честно говоря ни разу не видел, чтобы именно так добавляли. Если внутри файла svg, то clippath определяется в секции defs файла svg, а потом применяется уже к объекту svg в стилях этого же объекта - style ="url(#...);" Да вы лучше меня это знаете :) А вот форма url('data:image/svg+xml ... применяется обычно как фон для картинок с base64 За точность не отвечаю, так как практически никогда не пользовался такой формой включения svg изображения 30 мар 2017 в 9:34
  • Спасибо большое очень помогли !
    – brin gonor
    1 апр 2017 в 14:02
  • @brin gonor не стесняйтесь, задавайте вопросы, всегда рад помочь, если смогу, конечно. 1 апр 2017 в 14:05

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.