IconИконка
Иконка — небольшая векторная картинка размера и цвета окружающего текста. В наборе 848 рисунков, большинство в трёх темах, каждый — компонент, который импортируется по имени; Icon рисует ваши собственные.
Когда использовать
- Используйте иконку, чтобы кнопку, пункт меню или статус было легче узнать. Если смысл неочевиден, оставьте рядом слово.
- Импортируйте только нужные иконки из
svelte-ant-design/icons: сборка оставит эти рисунки и отбросит остальные из 848. - Используйте
Iconдля своего рисунка или для рисунка, который вы сами берёте из@ant-design/icons-svg.
Примеры
no props: the size and the color of the text
font-size and color set on the parent
inside a line of text
Your settings are saved .
<script lang="ts">
import { HomeOutlined, SettingOutlined, SmileOutlined } from 'svelte-ant-design/icons';
</script>
<div class="stack">
<div class="field">
<span class="caption">no props: the size and the color of the text</span>
<div class="row">
<HomeOutlined />
<SettingOutlined />
<SmileOutlined />
</div>
</div>
<div class="field">
<span class="caption">font-size and color set on the parent</span>
<div class="row big">
<HomeOutlined />
<SettingOutlined />
<SmileOutlined />
</div>
</div>
<div class="field">
<span class="caption">inside a line of text</span>
<p class="line">Your settings <SettingOutlined /> are saved <SmileOutlined />.</p>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 8px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
}
.big {
color: var(--ads-color-primary);
font-size: 28px;
}
.line {
margin: 0;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
StarOutlined, StarFilled, StarTwoTone
HeartOutlined, HeartFilled, HeartTwoTone
<script lang="ts">
import { HeartFilled, HeartOutlined, HeartTwoTone, StarFilled, StarOutlined, StarTwoTone } from 'svelte-ant-design/icons';
</script>
<div class="stack">
<div class="field">
<span class="caption">StarOutlined, StarFilled, StarTwoTone</span>
<div class="row">
<StarOutlined />
<StarFilled />
<StarTwoTone />
</div>
</div>
<div class="field">
<span class="caption">HeartOutlined, HeartFilled, HeartTwoTone</span>
<div class="row">
<HeartOutlined />
<HeartFilled />
<HeartTwoTone />
</div>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 8px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 16px;
font-size: 28px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
spin: the switch turns it on and off
the loading icon turns by itself
rotate: 0, 90, 180 and 270 degrees
rotate and spin together
<script lang="ts">
import { Switch } from 'svelte-ant-design';
import { ArrowUpOutlined, LoadingOutlined, RocketOutlined, SyncOutlined } from 'svelte-ant-design/icons';
let spinning = $state(true);
</script>
<div class="stack">
<div class="field">
<span class="caption">spin: the switch turns it on and off</span>
<div class="row">
<Switch bind:checked={spinning} aria-label="Spin" />
<SyncOutlined spin={spinning} />
</div>
</div>
<div class="field">
<span class="caption">the loading icon turns by itself</span>
<div class="row">
<LoadingOutlined />
</div>
</div>
<div class="field">
<span class="caption">rotate: 0, 90, 180 and 270 degrees</span>
<div class="row">
<ArrowUpOutlined rotate={0} />
<ArrowUpOutlined rotate={90} />
<ArrowUpOutlined rotate={180} />
<ArrowUpOutlined rotate={270} />
</div>
</div>
<div class="field">
<span class="caption">rotate and spin together</span>
<div class="row">
<RocketOutlined rotate={45} spin />
</div>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 8px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 16px;
font-size: 24px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
no twoToneColor: the theme colors
twoToneColor="#eb2f96", twoToneColor="#52c41a": the second color is derived
twoToneColor as a pair: [primary, secondary]
setTwoToneColor: the default of every two-tone icon of the page that has no color of its own getTwoToneColor(): var(--ads-icon-twotone-primary) / var(--ads-icon-twotone-secondary)
<script lang="ts">
import { Button, getTwoToneColor, setTwoToneColor } from 'svelte-ant-design';
import { CheckCircleTwoTone, HeartTwoTone, SmileTwoTone } from 'svelte-ant-design/icons';
import { onDestroy } from 'svelte';
// The colors the library starts with: the theme tokens. `setTwoToneColor` with them puts the default back.
const THEME = ['var(--ads-icon-twotone-primary)', 'var(--ads-icon-twotone-secondary)'] as [string, string];
// The global color belongs to the whole page; leaving this example puts the default back.
onDestroy(() => setTwoToneColor(THEME));
</script>
<div class="stack">
<div class="field">
<span class="caption">no twoToneColor: the theme colors</span>
<div class="row">
<SmileTwoTone />
</div>
</div>
<div class="field">
<span class="caption">twoToneColor="#eb2f96", twoToneColor="#52c41a": the second color is derived</span>
<div class="row">
<HeartTwoTone twoToneColor="#eb2f96" />
<CheckCircleTwoTone twoToneColor="#52c41a" />
</div>
</div>
<div class="field">
<span class="caption">twoToneColor as a pair: [primary, secondary]</span>
<div class="row">
<SmileTwoTone twoToneColor={['#1677ff', '#ffe58f']} />
<HeartTwoTone twoToneColor={['#722ed1', '#d3adf7']} />
</div>
</div>
<div class="field">
<span class="caption">setTwoToneColor: the default of every two-tone icon of the page that has no color of its own</span>
<div class="row">
<HeartTwoTone />
<Button size="small" onclick={() => setTwoToneColor('#fa8c16')}>Orange</Button>
<Button size="small" onclick={() => setTwoToneColor(THEME)}>Theme</Button>
</div>
<span role="status">getTwoToneColor(): {getTwoToneColor().join(' / ')}</span>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 8px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 16px;
font-size: 24px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
no label: an image named by the drawing (star)
label="Favourite": your own name, in your own language
label="": hidden from assistive technology, next to visible text
Notifications
<script lang="ts">
import { BellOutlined, StarOutlined } from 'svelte-ant-design/icons';
</script>
<div class="stack">
<div class="field">
<span class="caption">no label: an image named by the drawing (star)</span>
<div class="row">
<StarOutlined />
</div>
</div>
<div class="field">
<span class="caption">label="Favourite": your own name, in your own language</span>
<div class="row">
<StarOutlined label="Favourite" />
</div>
</div>
<div class="field">
<span class="caption">label="": hidden from assistive technology, next to visible text</span>
<div class="row">
<BellOutlined label="" />
<span>Notifications</span>
</div>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 8px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
font-size: 20px;
}
.row span {
font-size: 14px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
in a Button with text: the icon is hidden, the text names the button
in an icon-only Button: the button is named, the icon is hidden
an icon with onclick, role="button", tabindex and keys
stars: 0
<script lang="ts">
import { Button } from 'svelte-ant-design';
import { DeleteOutlined, SearchOutlined, StarOutlined } from 'svelte-ant-design/icons';
let stars = $state(0);
// An icon with a click handler is not a button by itself: it gets a role, a place in the tab order and the keys.
function onkeydown(event: KeyboardEvent) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
stars += 1;
}
}
</script>
{#snippet search()}
<SearchOutlined label="" />
{/snippet}
{#snippet remove()}
<DeleteOutlined label="" />
{/snippet}
<div class="stack">
<div class="field">
<span class="caption">in a Button with text: the icon is hidden, the text names the button</span>
<div class="row">
<Button type="primary" icon={search}>Search</Button>
</div>
</div>
<div class="field">
<span class="caption">in an icon-only Button: the button is named, the icon is hidden</span>
<div class="row">
<Button shape="circle" icon={remove} aria-label="Delete" />
</div>
</div>
<div class="field">
<span class="caption">an icon with onclick, role="button", tabindex and keys</span>
<div class="row">
<StarOutlined label="Add a star" role="button" tabindex={0} onclick={() => (stars += 1)} {onkeydown} style="cursor: pointer; font-size: 24px" />
</div>
<span role="status">stars: {stars}</span>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 8px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
icon: a definition, with spin, rotate and label like any other
children: your own svg inside the icon
<script lang="ts">
import { Icon, type IconDefinition } from 'svelte-ant-design';
// A drawing is data: a name, a theme and the nodes of an svg. This is the shape that `@ant-design/icons-svg` uses for its own.
const flag: IconDefinition = {
name: 'flag',
theme: 'filled',
icon: {
tag: 'svg',
attrs: { viewBox: '0 0 24 24', focusable: 'false' },
children: [{ tag: 'path', attrs: { d: 'M5 2h2v20H5zM8 3h12l-3 5 3 5H8z' } }]
}
};
</script>
{#snippet drop()}
<svg viewBox="0 0 24 24" width="1em" height="1em" fill="currentColor"><path d="M12 2C8 8 5 11 5 15a7 7 0 0 0 14 0c0-4-3-7-7-13z" /></svg>
{/snippet}
<div class="stack">
<div class="field">
<span class="caption">icon: a definition, with spin, rotate and label like any other</span>
<div class="row">
<Icon icon={flag} />
<Icon icon={flag} rotate={90} label="Flag, turned" />
</div>
</div>
<div class="field">
<span class="caption">children: your own svg inside the icon</span>
<div class="row">
<Icon label="Drop">
{@render drop()}
</Icon>
<Icon spin label="Drop, spinning">
{@render drop()}
</Icon>
</div>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 8px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 16px;
font-size: 28px;
color: var(--ads-color-primary);
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
component: a Svelte component that renders an svg (panda-svg.part.svelte, shown below the example)
<script lang="ts">
import { Icon } from 'svelte-ant-design';
import PandaSvg from './panda-svg.part.svelte';
</script>
<div class="stack">
<div class="field">
<span class="caption">component: a Svelte component that renders an svg (panda-svg.part.svelte, shown below the example)</span>
<div class="row">
<Icon component={PandaSvg} label="Panda" />
<Icon component={PandaSvg} label="Panda, big" style="font-size: 40px" />
<Icon component={PandaSvg} spin rotate={20} label="Panda, spinning" />
</div>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 8px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 16px;
font-size: 28px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
<!-- panda-svg.part.svelte -->
<script lang="ts">
// A custom drawing for Icon's `component` prop: it renders one svg and uses the width, the height and the fill it is given.
let { width = '1em', height = '1em', fill = 'currentColor' }: { width?: string; height?: string; fill?: string } = $props();
</script>
<svg viewBox="0 0 24 24" {width} {height} aria-hidden="true">
<circle cx="5.5" cy="5.5" r="3.5" {fill} />
<circle cx="18.5" cy="5.5" r="3.5" {fill} />
<circle cx="12" cy="13" r="9" fill="none" stroke={fill} stroke-width="2" />
<circle cx="8.5" cy="12" r="1.6" {fill} />
<circle cx="15.5" cy="12" r="1.6" {fill} />
</svg>
IconFont type="icon-ring", type="icon-square"
extraCommonProps: style for every icon of the font
<script lang="ts">
import { createFromIconfontCN } from 'svelte-ant-design';
// In your project `scriptUrl` is the address that your iconfont.cn project gives you, for example '//at.alicdn.com/t/font_xxx.js'.
// Here the sprite script is made on the page, so that the example works without a network. It does what that script does:
// it puts a <svg> with a <symbol id="icon-..."> for every icon at the start of the body.
const sprite = `(function () {
var holder = document.createElement('div');
holder.innerHTML = '<svg><symbol id="icon-ring" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="3"/></symbol>' +
'<symbol id="icon-square" viewBox="0 0 24 24"><rect x="4" y="4" width="16" height="16" rx="3" fill="currentColor"/></symbol></svg>';
var svg = holder.firstChild;
svg.style.position = 'absolute';
svg.style.width = 0;
svg.style.height = 0;
document.body.insertBefore(svg, document.body.firstChild);
})();`;
const scriptUrl = typeof document === 'undefined' ? '' : URL.createObjectURL(new Blob([sprite], { type: 'text/javascript' }));
const IconFont = createFromIconfontCN({ scriptUrl });
// `extraCommonProps` go to every icon of this font; the props of one icon win.
const Marker = createFromIconfontCN({ scriptUrl, extraCommonProps: { style: 'color: var(--ads-color-primary)' } });
</script>
<div class="stack">
<div class="field">
<span class="caption">IconFont type="icon-ring", type="icon-square"</span>
<div class="row">
<IconFont type="icon-ring" label="Ring" />
<IconFont type="icon-square" label="Square" />
<IconFont type="icon-ring" spin label="Ring, spinning" />
</div>
</div>
<div class="field">
<span class="caption">extraCommonProps: style for every icon of the font</span>
<div class="row">
<Marker type="icon-square" label="Square" />
<Marker type="icon-ring" label="Ring" rotate={45} />
</div>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 8px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 16px;
font-size: 28px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
Все иконки
Все рисунки набора — в виде компонента, который вы импортируете, в шести группах и в порядке списка Ant Design: все темы вместе или по одной. Нажмите на иконку, чтобы скопировать её имя. Логотипы принадлежат их владельцам. Некоторые рисунки выглядят неровно при некоторых размерах из-за пиксельной сетки (например, ShareAltOutlined в 12 px); это особенность рисунка, а не компонента.
Иконок: 848
Иконки направлений91
Иконки подсказок54
API
Готовая иконка, например StarOutlined, принимает перечисленные ниже свойства, кроме icon, component и children.
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| icon | Только у Icon. Данные одного рисунка: { name, theme, icon }, где icon — узлы svg, а у двухцветного рисунка — функция двух цветов. Подходит определение, импортированное из @ant-design/icons-svg. | IconDefinition | — |
| component | Только у Icon. Компонент Svelte, рисующий <svg>. Получает width и height в 1em и fill со значением currentColor. Приоритетнее icon. | Component<IconComponentProps> | — |
| children | Только у Icon. Своё содержимое, <svg>, рисуется внутри обёртки. Приоритетнее component и icon. | Snippet | — |
| spin | Вращает иконку (её обёртку) раз в секунду без остановки; медленнее при prefers-reduced-motion. Рисунок loading вращается и без него, а spin={false} это отключает. | boolean | false |
| rotate | Градусы, на которые повёрнут рисунок. Обёртка не поворачивается, поэтому spin и rotate работают вместе. Значение, не являющееся конечным числом, игнорируется. | number | — |
| twoToneColor | Цвета двухцветного рисунка: один цвет (второй — самый светлый оттенок его палитры) или пара [основной, второй]. Цвет не в виде литерала, например var(--x), оставляет второй цвет по умолчанию. Контурные и залитые рисунки его игнорируют. | string | [string, string] | — |
| label | Доступное имя. Без него имя — это имя рисунка на английском (star); у своего рисунка имени нет, и он скрыт. label="" прячет иконку от вспомогательных технологий. Переданный aria-label тоже считается именем. | string | — |
| class | Дополнительный CSS-класс обёртки рядом с ads-icon и ads-icon-<имя>. | string | — |
| style | Инлайн-стиль обёртки. Рисунок — квадрат 1em, поэтому font-size задаёт размер, а color цвет. | string | — |
| native attributes | Нативные атрибуты обёртки <span> (onclick, tabindex, role, title, data-*, aria-*) передаются ей. Иконка не добавляет остановку в порядок Tab. | HTMLAttributes<HTMLSpanElement> | — |
Отличия от Ant Design: класс обёртки —
ads-icon, а не anticon; spin медленнее при уменьшенной анимации, а spin={false} останавливает рисунок loading; свой рисунок без label скрыт; цвета двухцветных иконок по умолчанию следуют токенам темы. Строковые имена с загрузкой по сети (Angular) и провайдер значений по умолчанию не берутся. Рисунки и их имена приходят из @ant-design/icons-svg (MIT) — пакета данных, который используют и пакеты иконок Ant Design для React и Vue.Функции
| Функция | Описание | Тип |
|---|---|---|
| setTwoToneColor | Задаёт цвета всех двухцветных иконок без собственного twoToneColor. Уже показанная иконка меняется сразу. Вызывайте один раз при старте: на сервере значение общее для всех запросов, поэтому оно для одной темы, а не для одного пользователя. | (color: string | [string, string]) => void |
| getTwoToneColor | Текущая пара [основной, второй]. До вызова setTwoToneColor это два токена темы в виде строк var(...). Массив — копия. | () => [string, string] |
| createFromIconfontCN | Загружает спрайт-скрипт проекта iconfont.cn (по одному <script> на адрес, один раз, в порядке списка, поэтому более поздний перекрывает более ранний при одинаковом имени) и возвращает компонент иконки со свойством type. extraCommonProps передаются каждой иконке; свойства самой иконки приоритетнее. На сервере ничего не загружается. Имени у иконки нет, пока не задан label. | ({ scriptUrl, extraCommonProps }) => Component |
Дизайн-токены
| Токен | Описание | По умолчанию |
|---|---|---|
| --ads-icon-twotone-primary | Основной цвет двухцветной иконки без своего цвета. Следует основному цвету темы. | var(--ads-color-primary) |
| --ads-icon-twotone-secondary | Светлый цвет такой иконки: самый светлый оттенок основного цвета. У тёмной темы своё значение. | #e6f4ff |
Доступность
- Каждая иконка — это
<span role="img">с именем рисунка на английском (aria-label="star"); svg внутри скрыт от вспомогательных технологий. - На сайте на другом языке английское имя не подходит. Задайте
labelсо своим текстом илиlabel="", чтобы спрятать иконку рядом с видимым текстом: тогда у неё нет ни роли, ни имени. - У своего рисунка (
componentилиchildren) нет имени, поэтому он скрыт, пока не заданlabel. - Иконка не принимает фокус и не входит в порядок Tab. Для нажатия используйте
Buttonи пусть имя несёт он, либо добавьтеrole="button",tabindexи клавиши Enter и Space сами. - Светлая часть двухцветной иконки — украшение. По замыслу её контраст с белой страницей намного ниже 3:1, поэтому смысл нельзя передавать только ею.
- Вращение не озвучивается; сообщайте текстом, что идёт загрузка, как это делает
Spin. Приprefers-reduced-motionоборот медленнее (2,5 секунды), чего в Ant Design нет. - Проверено настоящим скринридером (Orca с Firefox): он читает рисунок как его имя и «image», вместо этого имени —
label, приlabel=""не читает ничего, кнопку — по её тексту или имени, если иконка внутри скрыта, а иконку сrole="button"— как кнопку с её подписью. Не проверено: NVDA, JAWS, VoiceOver и скринридер телефона.