SVG и CSS
На этой странице показано, как использовать CSS со специальным языком для создания графики: SVG (en-US) .
Вы сделаете небольшой пример, которые можно будет запустить в любом браузере с поддержкой SVG.
Общая информация: SVG
SVG (Scalable Vector Graphics) является подмножеством языка XML и предназначен для создания графики.
SVG можно использовать для статических изображений, а также для анимаций и создания пользовательских интерфейсов.
Как и прочие языки, основанные на XML, SVG поддерживает использование таблиц стилей CSS, что позволяет отделить различные варианты визуального отображения от структуры данных.
Кроме того, таблицы стилей, которые вы используете в других языках разметки документов, могут содержать ссылку на SVG графику, в тех местах, где необходимо изображение. Например, в таблице стилей, для вашего HTML документа, можно указать ссылку (URL) на SVG графику в свойстве background.
| На момент написания статьи (середина 2011 года), большинство современных браузеров имеет базовую поддержку SVG, в том числе Internet Explorer 9 и выше. Некоторые дополнительные возможности SVG не поддерживаются, либо поддерживаются лишь частично, в определённых браузерах. Для более подробной информации о текущей поддержке SVG, см. SVG tables on caniuse.com, либо в таблицах совместимости SVG element reference (en-US) , для информации о поддержке отдельных элементов.В остальные версии можно добавить поддержку SVG, установив дополнительный плагин, например, предоставленный компанией Adobe.Более подробная информация о SVG в Mozilla, представлена на станице SVG (en-US) в этой wiki. |
|---|
За дело: Демонстрация SVG
Создайте новый документ SVG, как обычный текстовый файл, doc8.svg . Скопируйте и вставьте содержимое блока ниже, убедитесь, что пролистали его полностью, чтобы скопировать все:
DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> svg width="600px" height="600px" viewBox="-300 -300 600 600" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink"> title>SVG demonstrationtitle> desc>Mozilla CSS Getting Started - SVG demonstrationdesc> defs> g id="segment" class="segment"> path class="segment-fill" d="M0,0 v-200 a40,40 0 0,0 -62,10 z"/> path class="segment-edge" d="M0,-200 a40,40 0 0,0 -62,10"/> g> g id="quadrant"> use xlink:href="#segment"/> use xlink:href="#segment" transform="rotate(18)"/> use xlink:href="#segment" transform="rotate(36)"/> use xlink:href="#segment" transform="rotate(54)"/> use xlink:href="#segment" transform="rotate(72)"/> g> g id="petals"> use xlink:href="#quadrant"/> use xlink:href="#quadrant" transform="rotate(90)"/> use xlink:href="#quadrant" transform="rotate(180)"/> use xlink:href="#quadrant" transform="rotate(270)"/> g> radialGradient id="fade" cx="0" cy="0" r="200" gradientUnits="userSpaceOnUse"> stop id="fade-stop-1" offset="33%"/> stop id="fade-stop-2" offset="95%"/> radialGradient> defs> text id="heading" x="-280" y="-270"> SVG demonstrationtext> text id="caption" x="-280" y="-250"> Move your mouse pointer over the flower.text> g id="flower"> circle id="overlay" cx="0" cy="0" r="200" stroke="none" fill="url(#fade)"/> use id="outer-petals" xlink:href="#petals"/> use id="inner-petals" xlink:href="#petals" transform="rotate(9) scale(0.33)"/> g> svg>
Создайте новый файл CSS, style8.css . копируйте и вставьте содержимое блока ниже, убедитесь, что пролистали его полностью, чтобы скопировать все:
/*** SVG demonstration ***/ /* page */ svg background-color: beige; > #heading font-size: 24px; font-weight: bold; > #caption font-size: 12px; > /* flower */ #flower:hover cursor: crosshair; > /* gradient */ #fade-stop-1 stop-color: blue; > #fade-stop-2 stop-color: white; > /* outer petals */ #outer-petals opacity: 0.75; > #outer-petals .segment-fill fill: azure; stroke: lightsteelblue; stroke-width: 1; > #outer-petals .segment-edge fill: none; stroke: deepskyblue; stroke-width: 3; > #outer-petals .segment:hover > .segment-fill fill: plum; stroke: none; > #outer-petals .segment:hover > .segment-edge stroke: slateblue; > /* inner petals */ #inner-petals .segment-fill fill: yellow; stroke: yellowgreen; stroke-width: 1; > #inner-petals .segment-edge fill: none; stroke: yellowgreen; stroke-width: 9; > #inner-petals .segment:hover > .segment-fill fill: darkseagreen; stroke: none; > #inner-petals .segment:hover > .segment-edge stroke: green; >
Откройте документ в вашем браузере с поддержкой SVG. Переместите указатель мыши на изображение.
Эта wiki не поддерживает вставку SVG в страницы, поэтому мы не имеем возможности продемонстрировать это здесь. Изображение будет выглядеть так:
Примечания к демонстрации:
- Документ SVG привязывается к таблице стилей общепринятым способом.
- SVG содержит собственные свойства CSS и их значения. Некоторые из них похожи на значения CSS для HTML.
Что дальше?
В этой демонстрации, ваш браузер с поддержкой SVG уже знает, как отображать элементы SVG. Таблица стилей всего лишь некоторым образом меняет отображение. То же самое происходит с документами HTML и XUL. Однако CSS можно использовать для любых документов XML, в которых нет предусмотренного по умолчанию способа отображения элементов. Данный пример продемонстрирован на следующей странице: Данные XML
Found a content problem with this page?
- Edit the page on GitHub.
- Report the content issue.
- View the source on GitHub.
This page was last modified on 6 авг. 2023 г. by MDN contributors.
SVG изображение встроено в CSS с помощью background-image
Вот SVG анимация при наведении на изображение.
Есть ли способ, где я могу избежать написания кода SVG дважды?
body < background-color: #181818; >a < -webkit-transition: all .3s ease; -moz-transition: all .3s ease; -o-transition: all .3s ease; transition: all .3s ease; width: 30px; height: 30px; display: inline-block; >#twitter < background-image: url("data:image/svg+xml,%3Csvg style='fill: %23777' enable-background='new 0 0 612 612' version='1.1' viewBox='0 0 612 612' xml:space='preserve' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='m612 116.26c-22.525 9.981-46.694 16.75-72.088 19.772 25.929-15.527 45.777-40.155 55.184-69.411-24.322 14.379-51.169 24.82-79.775 30.48-22.907-24.437-55.49-39.658-91.63-39.658-69.334 0-125.55 56.217-125.55 125.51 0 9.828 1.109 19.427 3.251 28.606-104.33-5.24-196.84-55.223-258.75-131.17-10.823 18.51-16.98 40.078-16.98 63.101 0 43.559 22.181 81.993 55.835 104.48-20.575-0.688-39.926-6.348-56.867-15.756v1.568c0 60.806 43.291 111.55 100.69 123.1-10.517 2.83-21.607 4.398-33.08 4.398-8.107 0-15.947-0.803-23.634-2.333 15.985 49.907 62.336 86.199 117.25 87.194-42.947 33.654-97.099 53.655-155.92 53.655-10.134 0-20.116-0.612-29.944-1.721 55.567 35.681 121.54 56.485 192.44 56.485 230.95 0 357.19-191.29 357.19-357.19l-0.421-16.253c24.666-17.593 46.005-39.697 62.794-64.861z'%3E%3C/path%3E%3C/svg%3E"); >#twitter:hover < background-image: url("data:image/svg+xml,%3Csvg style='fill: %2300aced' enable-background='new 0 0 612 612' version='1.1' viewBox='0 0 612 612' xml:space='preserve' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='m612 116.26c-22.525 9.981-46.694 16.75-72.088 19.772 25.929-15.527 45.777-40.155 55.184-69.411-24.322 14.379-51.169 24.82-79.775 30.48-22.907-24.437-55.49-39.658-91.63-39.658-69.334 0-125.55 56.217-125.55 125.51 0 9.828 1.109 19.427 3.251 28.606-104.33-5.24-196.84-55.223-258.75-131.17-10.823 18.51-16.98 40.078-16.98 63.101 0 43.559 22.181 81.993 55.835 104.48-20.575-0.688-39.926-6.348-56.867-15.756v1.568c0 60.806 43.291 111.55 100.69 123.1-10.517 2.83-21.607 4.398-33.08 4.398-8.107 0-15.947-0.803-23.634-2.333 15.985 49.907 62.336 86.199 117.25 87.194-42.947 33.654-97.099 53.655-155.92 53.655-10.134 0-20.116-0.612-29.944-1.721 55.567 35.681 121.54 56.485 192.44 56.485 230.95 0 357.19-191.29 357.19-357.19l-0.421-16.253c24.666-17.593 46.005-39.697 62.794-64.861z'%3E%3C/path%3E%3C/svg%3E"); >
Отслеживать
задан 25 ноя 2019 в 20:40
Alexandr_TT Alexandr_TT
109k 23 23 золотых знака 112 112 серебряных знаков 374 374 бронзовых знака
ассоциация:stackoverflow.com/q/50430277/7394871
29 янв 2020 в 16:33
1 ответ 1
Сортировка: Сброс на вариант по умолчанию
Известно, что если SVG изображение добавляется с помощью background-image , то оно теряет все преимущества формата SVG. В том числе, становится невозможно стилизовать изображение с помощью правил CSS: fill , stroke и т.д.
Но есть решение этой проблемы:
Идея состоит в том, чтобы использовать возможность применения фильтра, избежав тем самым, дублирования кода SVG. Вам просто нужно настроить различные значения, чтобы получить цвета, которые вы хотите.
body < background-color: #181818; >a < transition: all .3s ease; width: 30px; height: 30px; display: inline-block; >#twitter < background-image: url("data:image/svg+xml,%3Csvg style='fill: %2300aced' enable-background='new 0 0 612 612' version='1.1' viewBox='0 0 612 612' xml:space='preserve' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='m612 116.26c-22.525 9.981-46.694 16.75-72.088 19.772 25.929-15.527 45.777-40.155 55.184-69.411-24.322 14.379-51.169 24.82-79.775 30.48-22.907-24.437-55.49-39.658-91.63-39.658-69.334 0-125.55 56.217-125.55 125.51 0 9.828 1.109 19.427 3.251 28.606-104.33-5.24-196.84-55.223-258.75-131.17-10.823 18.51-16.98 40.078-16.98 63.101 0 43.559 22.181 81.993 55.835 104.48-20.575-0.688-39.926-6.348-56.867-15.756v1.568c0 60.806 43.291 111.55 100.69 123.1-10.517 2.83-21.607 4.398-33.08 4.398-8.107 0-15.947-0.803-23.634-2.333 15.985 49.907 62.336 86.199 117.25 87.194-42.947 33.654-97.099 53.655-155.92 53.655-10.134 0-20.116-0.612-29.944-1.721 55.567 35.681 121.54 56.485 192.44 56.485 230.95 0 357.19-191.29 357.19-357.19l-0.421-16.253c24.666-17.593 46.005-39.697 62.794-64.861z'%3E%3C/path%3E%3C/svg%3E"); filter:grayscale(100%) brightness(0.6); >#twitter:hover
How to add SVGs with CSS (background-image)
There are TWO methods for displaying SVG images as a CSS background image:
- Link directly to an SVG file
.your-class < background-image: url( '/path/image.svg' ); >
- Placing SVG code as the source.
.your-class < background-image: url( "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 600 200'%3E%3Cpath d='M10 10h123v123H10z'/%3E%3C/svg%3E" ); >
Notice with this method we have to treat the SVG code before it will work. In the example, we convert the SVG to a Data URI. You could even convert it to Base64, but that will result in a messier, longer code blob. It is a best practice to avoid Base64 in this case.
Tip: Use this SVG to CSS converter tool to quickly convert your SVG code into a data URI.
After you place your file path or SVG code into the background-image property, you can further tweak how the background displays. You see, the great thing about using an SVG as a CSS background-image is that they can be styled with CSS background properties.
The CSS background-image properties
Let’s review all the properties related to background-image and what they do.
- Background-attachment:
Example values: scroll; fixed; local;
The attachment specifies how the background moves relative to the user’s screen. When the user scrolls, the background can scroll along with a given section, or stay put ( fixed ).
- Background-position:
Example values: center; top left; 50% 50%; right 30px bottom 15px;
The background-position determines where the image is displayed within its container. The center keyword is great with large backgrounds and at making patterns symmetrical. With smaller backgrounds, you may reach for a combo of keywords and lengths to place the background image more precisely. - Background-size:
Example values: cover; contain; 500px 250px; auto;
This controls how big or small the image displays. A value of cover forces the image to fill its entire containing element in proportion, and either the excess width or height will get clipped. A value of contain is similar in that it fills its container in proportion, but without clipping. You can also provide a specific width and height value. - Background-repeat:
Example values: no-repeat; repeat; repeat-x;
The background-repeat property allows you to tile the background image into a pattern. - Background-color:
Example values: red; #F00; rgb(0,255,165);
SVGs are a transparent image format and if the SVG elements do not cover the entire viewBox, the background color will be visible behind your SVG. - Background-origin:
Example values: border-box; padding-box; content-box;
The origin determines the boundary of the background’s container. Border-box will stretch the background area for the entire container, while the padding-box and content-box values shrink the background area within the border and inside the padding respectively.
- Background-clip:
Example values: border-box; padding-box; content-box;
Similar to background-origin , this property defines the background area, with one difference: the background doesn’t resize, but instead crops the background image to fit in the assigned boundary.
- Background-blend-mode:
Example values: multiply; screen; overlay, color-dodge, color;
This property blends the colors of the target background with what is visible behind the target element, blending into a single colorful result. The blend modes are essentially the browser version of Photoshop’s blending modes.
Layering multiple background images
Background-image can hold multiple background image layers to achieve cool effects. To create these image layers, comma-separate each image value in a single background-image property. Then when you use any related background properties, comma-separate those varied values to coincide with the images, or instead use a single value which will apply to all images the same.
background-image: url( '/path/image-1.svg' ), url( '/path/image-2.svg' ), url( '/path/image-3.svg' );
You can mix images, SVG data URIs, and CSS gradients. But you need to overlap images with transparency or take advantage of the background-blend-mode discussed above. Otherwise you will only see one background. The first image is on top of the background stack.
Let’s mix a few backgrounds now, and see what we get. First I headed over to the homepage of SVGBackgrounds.com to find a few quick backgrounds to layer together. Here is the code and results:
BUT, this technique prevents the need to layer div containers to achieve a layer effect. Let’s try again, this time to make a simpler one that looks useable. Let’s place a pattern over a cool image texture.
Much better!
I could definitely see something more like this being used in a real-world project. Subtle backgrounds are always nice.
Wrapping up about SVGs in CSS background-images
We looked at how to add SVGs into the CSS property background-image . With all the related background properties and the fact you can layer backgrounds, there is little that can’t be achieved. This way of adding website backgrounds is powerful.
), the creator behind SVG Backgrounds. Hire me to help you with design on your website or app.
), the creator behind SVG Backgrounds. I produce free and paid resources every few months, sign up for alerts.
Как вставить svg как background?
Здравствуйте. SVG-картинку нужно сделать фоном для страницы. Если задать для элемента background: url(../img/back.svg) center/cover no-repeat, то такую конструкцию понимают только файрфокс и ie. Хром и опера не выводят этот бэкграунд. Кто виноват и что делать?
- Вопрос задан более трёх лет назад
- 12997 просмотров
Комментировать
Решения вопроса 1
Евгений Журов @Zhuroff Автор вопроса
Разобрался, проблема была действительно в самом svg-файле. Нужно, чтобы внутри было
xlink:href html»>xlink:href answer__date»> Ответ написан более трёх лет назад
Комментировать
Нравится 2 Комментировать
