Html input button icon

Как сделать кнопку в HTML

Для создания кнопок используется тег . Внутри него размещается текст или изображение, которые будут отображаться на кнопке. Например:

Чтобы задать кнопке имя, тип или состояние, нужно добавить атрибуты: name , disabled и type .

Атрибут name задаёт имя кнопки. Может использоваться для идентификации элемента в скриптах.

Атрибут disabled блокирует доступ к кнопке.

Атрибут type определяет тип кнопки. Ему задают одно из трёх значений:

button — значение по умолчанию. Означает, что элемент — обычная кнопка. Она может добавлять товары в корзину или избранное, переключать слайдеры или закрывать всплывающие окна.

submit задаётся кнопкам для отправки формы. Когда пользователь нажимает на кнопку с таким типом, браузер отправляет данные формы на сервер.

reset добавляется кнопкам сброса формы. Когда пользователь нажимает на такую кнопку, браузер возвращает значения всех полей формы к изначальным.

Читайте также:  Javascript class set get

А как же input?

Создать кнопку можно и с помощью тега , если указать ему тип button :

Это рабочий способ. О нём надо знать, ведь вы можете встретить его в проектах. Но самим так делать не стоит. У кнопок, созданных на инпуте, есть ограничения: сложно управлять размерами и положением изображений, а также нет псевдоэлементов. Поэтому оставьте для создания элементов формы, таких как текстовые поля, радиокнопки или чекбоксы. А кнопки верстайте с помощью .

Как сделать кнопку с иконкой

Посмотрим три способа создания кнопки с иконкой.

С помощью тега

Способ подойдёт для контентных изображений.

Кнопки с контентным изображением

Так вы можете добавлять кнопки с эмодзи, лайками, дизлайками или чем-то ещё. Иконке нужно обязательно задавать размеры, чтобы кнопка зарезервировала место и не прыгала, когда загрузится иконка.

Добавить инлайн SVG в разметку

Способ подойдёт, если изображение меняет состояния, как здесь:

Код простой: пишем тег и добавляем в него код SVG-изображения.

Вставить фоном в CSS

Способ подойдёт, если иконка играет декоративную роль и не меняется при наведении или клике на кнопку. Например, в таких случаях:

Как добавить иконку в кнопку:

Какой способ выбрать — зависит от ваших задач и особенностей проекта. Вы также можете использовать разные методы в рамках одного проекта. Например, часть кнопок сделать со встроенным в разметку SVG, а часть — с фоновым изображением.

Материалы по теме

«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.

Источник

5 Different Methods to Add Icons to HTML Input Type Buttons

Learn how to add icons to HTML input type buttons using 5 different methods, including Font Awesome and image icons. Enhance user experience and make your website visually appealing.

  • Introduction
  • Using the and tag to add Font Awesome icons to buttons
  • CSS — ( Part 2 : Adding Icon ) Simple Input Text Box
  • Using for adding an icon in a button
  • Using anchor tag to add an icon to a button
  • To add an image icon to a button, use tag and tag
  • Using the tag to add an image icon to input type=»submit”
  • Other quick code examples for adding icons to HTML input type buttons
  • Conclusion
  • How do I put an icon inside an input button?
  • How to add image icon to button in HTML?
  • How do I add Font Awesome icon to input type button?
  • Can we add icon in button?

Icons are a crucial part of modern web design. They are more than just decorative elements, as they help users to understand the purpose of different elements on the webpage. One of the essential elements of web design is the input type buttons. In this article, we will explore five different methods to add icons to html input type buttons.

Introduction

HTML input type buttons are an essential element of web design. They help users to submit forms, navigate through web pages, and perform various other actions. Adding icons to HTML input type buttons can significantly enhance the user experience and make the website more visually appealing. However, adding icons to input type buttons is not as straightforward as it seems. In this article, we will explore five different methods to add icons to HTML input type buttons.

Using the and tag to add Font Awesome icons to buttons

Font Awesome is a popular icon library that provides scalable vector icons that can be customized as per the requirements. It is incredibly easy to use Font Awesome icons in HTML input type buttons using the and tags. Here are the steps to add Font Awesome icons to input type buttons:

  1. Include the Font Awesome CSS file in the HTML document.
  2. Choose the desired icon from the Font Awesome library.
  3. Add the tag with the class “fa” and the icon class, such as “fa-user.”
  4. Add the tag with the desired text for the button.

Here is an example of how to use Font Awesome icons in HTML input type buttons:

button type="submit"> i class="fa fa-user">i> span>Loginspan> button> 

Supporting Points

  • Customizing the style of the icon: font awesome icons can be customized using css to match the website’s overall design and theme.
  • Examples of Font Awesome icons that can be used in buttons: Font Awesome provides a vast collection of icons for various purposes, such as social media, navigation , and user interface.
  • best practices for using font awesome icons in buttons: It is essential to choose the right icon for the button’s purpose and ensure that the icon is visible and understandable to all users.

CSS — ( Part 2 : Adding Icon ) Simple Input Text Box

Using for adding an icon in a button

The tag is another way to add icons to HTML input type buttons. It provides more flexibility and control over the button’s behavior and appearance than the tag. Here is how to add an icon to a button using :

  1. Add the tag with the desired text for the button.
  2. Add the “type” attribute with the value “reset.”
  3. Add the desired icon using CSS.

Here is an example of how to use to add an icon to a button:

button type="reset"> span class="icon">span> span>Resetspan> button> 

Supporting Points

  • Advantages of using instead of for adding icons to buttons : provides more functionality and customization options than .
  • Examples of icons that can be added using : The reset icon, refresh icon, and undo icon are some of the icons that can be added using .

Using anchor tag to add an icon to a button

Here is an example of how to use to add an icon to a button:

a href="#" class="button"> span class="icon">🔍span> span>Searchspan> a> 

Supporting Points

To add an image icon to a button, use tag and tag

Adding image icons to HTML input type buttons is another way to enhance the user experience. It provides more visual cues and helps users to understand the button’s purpose more quickly. Here is how to add an image icon to a button using the tag and the tag:

  1. Add the tag with the desired text for the button.
  2. Add the tag with the desired image source and alt attribute.

Here is an example of how to use the tag and the tag to add an image icon to a button:

button type="submit"> img src="icon.png" alt="Submit"> span>Submitspan> button> 

Supporting Points

  • Advantages of using image icons over Font Awesome icons: Image icons provide more customization options and better quality than Font Awesome icons.
  • Examples of image icons that can be added to buttons: Company logos, product images, and custom icons are some of the image icons that can be added to buttons.

Using the tag to add an image icon to input type=»submit”

The tag is primarily used to associate a form element with its label, but it can also be used to add image icons to HTML input type=»submit”. Here is how to add an image icon to input type=»submit” using the tag:

  1. Add the tag with the type=»submit” attribute.
  2. Add the tag with the “for” attribute that matches the “id” attribute of the input tag.
  3. Add the tag with the desired image source and alt attribute.

Here is an example of how to use the tag to add an image icon to input type=»submit»:

label for="submit-button" class="button"> img src="icon.png" alt="Submit"> label> input type="submit" id="submit-button" value="Submit"> 

Supporting Points

  • Advantages of using instead of for adding image icons: provides better accessibility and usability than .
  • Examples of image icons that can be added using : Company logos, product images, and custom icons are some of the image icons that can be added using .

Other quick code examples for adding icons to HTML input type buttons

Conclusion

In this article, we have explored five different methods to add icons to HTML input type buttons. Adding icons to input type buttons can significantly enhance the user experience and make the website more visually appealing. However, it is essential to consider accessibility when adding icons to buttons. The right icon should be chosen for the button’s purpose, and it should be visible and understandable to all users. By following the methods described in this article, you can add icons to input type buttons easily and effectively.

Источник

Create a search icon inside input box with HTML and CSS

Displaying a search icon inside an input box is a nice way to indicate to the user that it is indeed a search input.

Google search input Duckduckgo search input Twitter search input CodePen search input Gmail search input Vimeo search input

Markup

The HTML for our search box with an icon will consist of a form , input , and button elements.

  type="search" placeholder="Search. ">  type="submit">Search  

The form will act as a wrapper, as well as will react to the submit event.

The input element should have a type attribute equal to the search value. It will ensure a better usability on mobile devices. The keyboard with a layout suited for search will be shown.

💡 NOTE: To improve UX you can also specify an input placeholder e.g. «Search…». This will give a user an additional hint that this is indeed a search input.

Finally, the button type attribute should have a submit value. The proper button type will ensure the form can be submitted via button click without additional events for this button. The button will also act as an icon.

Styling

First, we’ll need to set the form element display property value to flex . This will allow us to properly align input and button elements.

We’ll also set a border property to wrap elements closer together.

form  color: #555; display: flex; padding: 2px; border: 1px solid currentColor; border-radius: 5px; > 

Next, we need to set styles for our search input box. It should span the full width of the container element, as well as have some visually appealing properties.

input[type="search"]  border: none; background: transparent; margin: 0; padding: 7px 8px; font-size: 14px; color: inherit; border: 1px solid transparent; border-radius: inherit; > input[type="search"]::placeholder  color: #bbb; > 

Finally, let’s add some styling to the submit button. We will hide the text of the button with text-indent and overflow properties, and display in its place a magnifying glass icon.

To display the icon we can use encoded svg as a background image.

button[type="submit"]  text-indent: -999px; overflow: hidden; width: 40px; padding: 0; margin: 0; border: 1px solid transparent; border-radius: inherit; background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'%3E%3Cpath d='M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z'%3E%3C/path%3E%3C/svg%3E") no-repeat center; cursor: pointer; opacity: 0.7; > button[type="submit"]:hover  opacity: 1; > 

The last touch is to set the :focus state on input and button elements:

button[type="submit"]:focus, input[type="search"]:focus  box-shadow: 0 0 3px 0 #1183d6; border-color: #1183d6; outline: none; > 

💡 NOTE: Since it’s a search input, you might want to display a clear button as well.

No button example

If you’re willing to show an icon inside an input without it being a button, just remove the submit button from the form.

 class="nosubmit">  class="nosubmit" type="search" placeholder="Search. ">  

You can leave existing form and input styles but in this case, set the icon as a background for the input.

form.nosubmit  border: none; padding: 0; > input.nosubmit  width: 260px; border: 1px solid #555; display: block; padding: 9px 4px 9px 40px; background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'%3E%3Cpath d='M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z'%3E%3C/path%3E%3C/svg%3E") no-repeat 13px center; > 

Demo

You can find a full demo with a complete code examples on my CodePen:

See the Pen Untitled by Tippingpoint Dev (@tippingpointdev) on CodePen.

Источник

Оцените статью