- Как сделать кнопку в HTML
- А как же input?
- Как сделать кнопку с иконкой
- С помощью тега
- Добавить инлайн SVG в разметку
- Вставить фоном в CSS
- Материалы по теме
- How to Create Image Button in HTML?
- Pre-requisites
- What Are We Creating?
- Creating Image Button in HTML
- Styling with CSS
- Conclusion
- CSS Button Image
- Example 01: Using the CSS Style Tag to Add an Image in a Button in an HTML File
- Example 02: Adding an Image in a Button Using an Inline CSS Approach
- Example 03: Using the CSS Style Tags to Add an Image to a Button When it Hovers Over
- Example 04: CSS Style Tag Transformation of a Default Button to an Icon for the Next and Previous Function
- Conclusion
- About the author
- Aqsa Yasin
Как сделать кнопку в HTML
Для создания кнопок используется тег . Внутри него размещается текст или изображение, которые будут отображаться на кнопке. Например:
Чтобы задать кнопке имя, тип или состояние, нужно добавить атрибуты: name , disabled и type .
Атрибут name задаёт имя кнопки. Может использоваться для идентификации элемента в скриптах.
Атрибут disabled блокирует доступ к кнопке.
Атрибут type определяет тип кнопки. Ему задают одно из трёх значений:
button — значение по умолчанию. Означает, что элемент — обычная кнопка. Она может добавлять товары в корзину или избранное, переключать слайдеры или закрывать всплывающие окна.
submit задаётся кнопкам для отправки формы. Когда пользователь нажимает на кнопку с таким типом, браузер отправляет данные формы на сервер.
reset добавляется кнопкам сброса формы. Когда пользователь нажимает на такую кнопку, браузер возвращает значения всех полей формы к изначальным.
А как же input?
Создать кнопку можно и с помощью тега , если указать ему тип button :
Это рабочий способ. О нём надо знать, ведь вы можете встретить его в проектах. Но самим так делать не стоит. У кнопок, созданных на инпуте, есть ограничения: сложно управлять размерами и положением изображений, а также нет псевдоэлементов. Поэтому оставьте для создания элементов формы, таких как текстовые поля, радиокнопки или чекбоксы. А кнопки верстайте с помощью .
Как сделать кнопку с иконкой
Посмотрим три способа создания кнопки с иконкой.
С помощью тега
Способ подойдёт для контентных изображений.
Так вы можете добавлять кнопки с эмодзи, лайками, дизлайками или чем-то ещё. Иконке нужно обязательно задавать размеры, чтобы кнопка зарезервировала место и не прыгала, когда загрузится иконка.
Добавить инлайн SVG в разметку
Способ подойдёт, если изображение меняет состояния, как здесь:
Код простой: пишем тег и добавляем в него код SVG-изображения.
Вставить фоном в CSS
Способ подойдёт, если иконка играет декоративную роль и не меняется при наведении или клике на кнопку. Например, в таких случаях:
Как добавить иконку в кнопку:
Какой способ выбрать — зависит от ваших задач и особенностей проекта. Вы также можете использовать разные методы в рамках одного проекта. Например, часть кнопок сделать со встроенным в разметку SVG, а часть — с фоновым изображением.
Материалы по теме
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
How to Create Image Button in HTML?
In this article, we’ll learn how to make an image button in HTML using some CSS. Usually, we see text on a button, but in this article, we will make an image button in HTML.
Having an image as a button is better sometimes because an image is more visually appealing, and sometimes it sends a clearer message than text.
We can make an image a button in two simple ways. First, we can make use of the tag and place a tag inside it. Second, we can make use of the anchor tag and place a inside it.
In this article, we are going to learn about the first method, i.e., using the tag.
Pre-requisites
What Are We Creating?
Let’s see what we are going to create here. We are going to make an email newsletter subscription section. It’ll have a heading, an input field, and, most important, an image as a button.
We used a tag with a type attribute as email. In the submit button of the newsletter, we have used an image and added some cool hover effects. As you can see, the image rotates 360deg when the mouse pointer hovers over it.
Creating Image Button in HTML
Let’s first set up our index.html file and add the structure. Then we will add some CSS to make it look better.
It’s a simple HTML code. Inside the body tag, we will use the div tag and put everything that we need inside it. It is good practice to keep your code organized like this, and it will also make the button and image element block because div is a block element, so anything inside it will also become a block.
Inside the div, we will add an email field to get the email of the user.
To make an image button in HTML, we will use the tag inside the tag. So in this way, the image will behave like a button.
In the src attribute of the image tag, we write the address of the image we want to use.
That is all that we have to do inside the body tag. Let’s see what our newsletter signup looks like without any CSS.
Styling with CSS
After setting up the structure of our newsletter subscription form, it’s time to style it with CSS and give it some visual appeal.
We are adding CSS to undo some CSS applied by default, like margin, padding, and properties like border, appearance, and background color that are applied to the button element by default.
We also want to add some of our CSS, like we want to have a hover effect and we want to center the button.
After combining all the bits and pieces of the code snippets, our code will look like this.
The complete code:
Final Output:
This is how we make an image button in HTML.
Conclusion
To use an image as a button in HTML, we use:
- A tag.
- Inside the tag, we use the tag with the link of the source image inside the src attribute of the image tag.
Using an image as a button makes the button more visually appealing and adds meaning to the button.
CSS Button Image
We will be using CSS on the button element of the Hypertext Markup Language in this article. Usually, the default button element is very simple and has no styling and effects present in it. With the help of CSS, we use the different styling properties and add them to this element. These properties are related to text styling, size adjustment, background colors, animation effects, and adding images. In this article, we will primarily focus on adding an image to a button property that is applicable through CSS. To implement this approach, we will be using the Notepad++ which will help us in editing our HTML file and test run it on our browser.
Example 01: Using the CSS Style Tag to Add an Image in a Button in an HTML File
In this example, we will add an image inside a button using the CSS Style Tag in the file header. Inside the Style Tag, we will construct a class for the button, which will be called later in the body. Then, we will create a script in which we will add an image to a button using the technique we previously mentioned.
In the previous script, we opened a Style Tag in the file header. In this tag, we open the button class parameters in which we will define several designing properties for the button element. First, we add the image for the button’s background. We can add the image via “URL” or “src”. Then we add the background-size property which is stated as a “cover”. Then we define the width and height of the button as well. After this, we close the Style Tag and move to the body tag. In this tag, we add a heading using the h1 tag. Then, the button tag is called. In this tag, we call the styling class that we created earlier to inherit all the styling that are defined in the class. Then, we close all the remaining tags and save the file in the HTML format.
As we can see in the previous output, the image appears as a button on our browser’s page along with the heading. This justifies that the styling class was successfully inherited by the button tag.
Example 02: Adding an Image in a Button Using an Inline CSS Approach
In this instance, we will add an image to a button using the Inline CSS approach. We will add an image to a default button element of the Hypertext Markup Language by giving it an image’s URL in this method. Now, let us take a look at the script for this technique.:
In the script reflected in the image, we can see that the file header is empty because we will use the Inline CSS approach in this example. We open our button tag. In the tag, we mention the CSS that we want the button to have in the style property. We mention all the styling in this property and separate them with semicolons. We also add an image using the background image keyword and assign an image via URL. Then the button tag is closed along with the body tag. After this, we open this HTML file on our browser.
The previous output is an evidence that the Inline Style Tag approach has been a success. We can see that the image is added to the button and the default button is now transformed into an image.
Example 03: Using the CSS Style Tags to Add an Image to a Button When it Hovers Over
We will add an image to a button that will appear only when the button is hovered upon in this example. We will use the Style Tag CSS to provide a button with such behavior in an HTML file. We will create a separate class to segregate this styling for a specific element in this example. To achieve this goal, we should write the following script:
In the previous script, we opened our head tag for the HTML file. In this tag, the styling of the button is defined by opening a class for the button element. In this class, we define the width and the height of the button first. Then, we add a property that turns the cursor into a pointer, and we give the text a reasonable size as well. Then, we add an inherited method called “hover” to the class. In this function, we add an image to the background via URL and assign a property to the background size called the “cover”.
After this, we close all the styling tags and move toward the body of this file. In the body tag, we add a heading using the h1 tag and the button tag is opened after the heading tag. In the button tag, we call the class that we created in the Style Tag of the file’s header. And then, close the button and body tag. After this, we open this file in our browser to get the following output:
The output that we see in this file is the result after the button has been hovered upon. When we hover over the button, the image that we assigned in the Style Tag of the file header appears.
Example 04: CSS Style Tag Transformation of a Default Button to an Icon for the Next and Previous Function
In this example, we will transform the two default buttons of the Hypertext Markup Language by using the CSS Style Tag. We will transform the two buttons in this example into the next and previous icons by adding an image in the Style Tag. We should write the following script to do so:
In the previous script, we add a Style Tag in the file header. Then, we create two classes for the two buttons in the Style Tag. In these classes, we add an image to both the buttons respectively, using the background image property and the URL format for the image. After assigning both classes with their properties, we close the style and head tag and open the body tag to create the content for our browser’s page. First, we give the border a heading with the help of the h1 tag, which is a heading size defined in HTML. Then, we create two buttons. In both these buttons, we assign the relative class defined in the Style Tag. After this, we close the tabs and open this file on our browser after saving it.
The previous output is the outcome of our script. As we can see, both the buttons are aligned and the images from the style classes are inserted correctly. Now, the default buttons are transformed into the next and previous icons for a web page by using CSS.
Conclusion
In this article, we discussed several examples of adding the images to a button using CSS. We used the Inline CSS and Style Tag CSS to add the images to a default button in an HTML file. We implemented several effects on a button to add an image like the hover effect or cover style background by using the Notepad++ to edit the HTML file. We used the different properties in the CSS styling of the button element to transform them into an attractive attribute in our webpage.
About the author
Aqsa Yasin
I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.