- How to add an icon inside the button using CSS
- Step:1
- Step:2
- Add an icon inside the button Video Output:
- Icon Button CSS Styling Guide
- Icon + Text Button
- Icon Styling for Icon + Text
- Icon-Only Buttons
- Demo
- What to Read Next
- Как сделать кнопку в HTML
- А как же input?
- Как сделать кнопку с иконкой
- С помощью тега
- Добавить инлайн SVG в разметку
- Вставить фоном в CSS
- Материалы по теме
How to add an icon inside the button using CSS
First, we need to create two files index.html and style.css then we need to do code for it.
Step:1
Add below code inside index.html
lang="en"> charset="UTF-8" /> How to add icon inside button using CSS Only name="viewport" content="width=device-width, initial-scale=1.0" /> http-equiv="X-UA-Compatible" content="ie=edge" /> rel="stylesheet" href="style.css" /> href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans&display=swap" rel="stylesheet"> class="button-outer"> class="button"> Book Now
Step:2
Then we need to add code for style.css which code I provide in the below screen.
@import url(https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css); * padding: 0; margin: 0; font-family: 'IBM Plex Sans', sans-serif; > body display: flex; align-items: center; justify-content: center; height: 100vh; > .button font-size: 25px; padding: 10px 20px; background: #3f0069; border: unset; color: #fff; cursor: pointer; box-shadow: 0 0 2px #000; outline: 0; position: relative; > .button:before content: "\f017"; display: inline-block; font: normal normal normal 14px/1 FontAwesome; font-size: inherit; text-rendering: auto; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; >
Add an icon inside the button Video Output:
Icon Button CSS Styling Guide
This is episode #10 in a series examining modern CSS solutions to problems Stephanie Eckles has been solving over the last 15+ years as a front-end dev.
This guide will build on the previous episode «CSS Button Styling Guide» to explore the use case of icon buttons. We’ll cover icon + text as well as icon-only buttons.
Note: With SVG now having excellent support, the preferred practice is to use it for icon systems vs. icon fonts. We will not dive into SVGs specifically, but we will assume SVG icons are in use.
Icon + Text Button
First, let’s do the easier extend from our current buttons, and drop an svg icon next to the text:
a href="javascript:;" class="button"> svg class="button__icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" aria-hidden="true" focusable="false" > path d="M32 12.408l-11.056-1.607-4.944-10.018-4.944 10.018-11.056 1.607 8 7.798-1.889 11.011 9.889-5.199 9.889 5.199-1.889-11.011 8-7.798z" >path> svg> Button Link a>
There are 3 key features about the SVG for the icon + text use case:
- Use of a new button__icon class
- The viewBox value is tight to the icon boundaries, ideally a square for best results across the icon set even if the values have variance (ex. 24 vs. 32 )
- For accessibility, we apply:
- aria-hidden=»true» — allows assistive tech to skip the SVG since it’s decorative and not providing any semantic value not already provided by the visible button text
- focusable=»false» — prevents a «double focus» event in some version of IE
For more on accessibility of icon buttons: Read this excellent article by Sara Soueidan who is an expert on both accessibility and SVGs
Icon Styling for Icon + Text
Due to display: inline-flex applied on the base .button , and no width attribute on the SVG, by default the icon is not yet visible.
So let’s first add dimensions to our new .button__icon class, using the em unit to keep it relative to the font-size in use:
.button__icon // You may wish to have your icons appear larger // or smaller in relation to the text width: 0.9em; height: 0.9em; >
According to the spec default, SVG parts including path have a fill of black. To adjust this, we will use the special keyword currentColor which will extend the button’s applied text color to the SVG:
.button__icon // . existing styles fill: currentColor; >
The last thing to adjust is to add a bit of spacing between the icon and button text, which we will again apply using the em unit:
.button__icon // . existing styles margin-right: 0.5em; >
We need to add one utility class to allow the icon to be placed after the text, or at the «end» of the button (for right-to-left languages). We zero out the existing margin, and flip it to the left:
.button__icon // . existing styles &--end margin-right: 0; margin-left: 0.5em; > >
a href="javascript:;" class="button"> Button Link svg class="button__icon button__icon--end" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" aria-hidden="true" focusable="false" > path d="M32 12.408l-11.056-1.607-4.944-10.018-4.944 10.018-11.056 1.607 8 7.798-1.889 11.011 9.889-5.199 9.889 5.199-1.889-11.011 8-7.798z" >path> svg> a>
Join my newsletter for article updates, CSS tips, and front-end resources!
Icon-Only Buttons
We’re going to make the assumption that we want both regular buttons (with or without icons) in addition to icon-only buttons. This is important because we will reuse the .button class in addition to a new class so that we don’t have to redefine the resets and base visual styles. The overrides are minimal.
a href="javascript:;" class="button icon-button" aria-label="Icon-only Button"> svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" aria-hidden="true" class="icon-button__icon" aria-hidden="true" focusable="false" > path d="M32 12.408l-11.056-1.607-4.944-10.018-4.944 10.018-11.056 1.607 8 7.798-1.889 11.011 9.889-5.199 9.889 5.199-1.889-11.011 8-7.798z" >path> svg> a>
Changes from the icon + text button:
- Addition of the icon-button class to the a
- Addition of aria-label=»Icon-only Button» to provide an accessible text alternative since we have removed the visual text
- Swap of the class on the SVG to icon-button__icon
Important: the value of the aria-label should describe what the button does not what the icon is. For further reading and other ways to provide a text alternative, see Sara Soueidan’s article
Here’s what we get before adjustments — an empty-looking button because we’re back to the no-width problem:
First, let’s create our new class. Due to the «C» in CSS, this rule needs to be placed after the .button rule:
.icon-button width: 2.5rem; height: 2.5rem; padding: 0.35em; border-radius: 50%; &__icon width: 100%; height: 100%; fill: currentColor; > >
We define a new width and height which is completely adjustable based on your design requirements, but it should equate to a square. This allows creation of a «circle» appearance when border-radius: 50% is applied.
Then, we add a touch of padding (again to your tastes/design requirements) to add some breathing room between the SVG icon and the button boundary.
Next, we define our icon-button__icon class. The difference here is that we want the width and height to match that of the container, so we set this to 100% . This allows extending to multiple size icon-only buttons by only redefining the font-size property on the .icon-button class.
It’s not quite what we want, but we can fix it by adjusting the following properties within the .button class. We’ll use the :not() selector to exclude the properties meant only for regular buttons:
.button // . existing styles // Find these styles and update, not duplicate: &:not(.icon-button) min-width: 10ch; min-height: 44px; padding: 0.25em 0.75em; > >
Now we have what we’re after:
Demo
Includes use of the .button—small class created in the previous episode, as well as a «real button» to validate that styles work just as well for both elements:
Try out ButtonBuddy to create accessible button colors. This web app I created will help get all the vectors of contrast right across your button color palette.
What to Read Next
Pure CSS Custom Checkbox Style We’ll create custom, cross-browser, theme-able, scalable checkboxes in pure CSS. We’ll use `currentColor`, the `em` unit, SVG, and CSS grid layout.
Guide to Advanced CSS Selectors — Part Two Continuing from part one, this episode will focus on the advanced CSS selectors categorized as pseudo classes and pseudo elements and practical applications for each.
CSS Tips in Your Inbox Join my newsletter for article updates, CSS tips, and front-end resources! Newsletter Signup
Custom Select Styles with Pure CSS Modern CSS gives us a range of properties to achieve custom select styles that have a near-identical initial appearance. This solution uses CSS grid, `clip-path`, and CSS custom properties.
Как сделать кнопку в HTML
Для создания кнопок используется тег . Внутри него размещается текст или изображение, которые будут отображаться на кнопке. Например:
Чтобы задать кнопке имя, тип или состояние, нужно добавить атрибуты: name , disabled и type .
Атрибут name задаёт имя кнопки. Может использоваться для идентификации элемента в скриптах.
Атрибут disabled блокирует доступ к кнопке.
Атрибут type определяет тип кнопки. Ему задают одно из трёх значений:
button — значение по умолчанию. Означает, что элемент — обычная кнопка. Она может добавлять товары в корзину или избранное, переключать слайдеры или закрывать всплывающие окна.
submit задаётся кнопкам для отправки формы. Когда пользователь нажимает на кнопку с таким типом, браузер отправляет данные формы на сервер.
reset добавляется кнопкам сброса формы. Когда пользователь нажимает на такую кнопку, браузер возвращает значения всех полей формы к изначальным.
А как же input?
Создать кнопку можно и с помощью тега , если указать ему тип button :
Это рабочий способ. О нём надо знать, ведь вы можете встретить его в проектах. Но самим так делать не стоит. У кнопок, созданных на инпуте, есть ограничения: сложно управлять размерами и положением изображений, а также нет псевдоэлементов. Поэтому оставьте для создания элементов формы, таких как текстовые поля, радиокнопки или чекбоксы. А кнопки верстайте с помощью .
Как сделать кнопку с иконкой
Посмотрим три способа создания кнопки с иконкой.
С помощью тега
Способ подойдёт для контентных изображений.
Так вы можете добавлять кнопки с эмодзи, лайками, дизлайками или чем-то ещё. Иконке нужно обязательно задавать размеры, чтобы кнопка зарезервировала место и не прыгала, когда загрузится иконка.
Добавить инлайн SVG в разметку
Способ подойдёт, если изображение меняет состояния, как здесь:
Код простой: пишем тег и добавляем в него код SVG-изображения.
Вставить фоном в CSS
Способ подойдёт, если иконка играет декоративную роль и не меняется при наведении или клике на кнопку. Например, в таких случаях:
Как добавить иконку в кнопку:
Какой способ выбрать — зависит от ваших задач и особенностей проекта. Вы также можете использовать разные методы в рамках одного проекта. Например, часть кнопок сделать со встроенным в разметку SVG, а часть — с фоновым изображением.
Материалы по теме
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.