Как сделать кнопку в виде картинки html
Перейти к содержимому

Как сделать кнопку в виде картинки html

  • автор:

Buttons and Icons

Styling hyperlinks as faux buttons with solid colour, gradient or transparent backgrounds, and adding Font Awesome icons to buttons.

WEB DESIGN COURSE

THIS TUTORIAL

At the end of this Tutorial, you will be able to:

  • Style hyperlinks as faux buttons with solid colour, gradient or transparent backgrounds.
  • Apply soft corners and rounded edges to faux buttons.
  • Add Font Awesome icons to faux buttons.

You can view the finished version of the sample web page you will create in this Tutorial by clicking the image below. The finished sample will open in a new tab of your web browser.

About buttons on web pages

Buttons on web pages can be of two types:

  • Real buttons: These connect user actions to back-end software that runs on the webserver. For example, they may submit a request to process an order, join an online service or subscribe to email list. Real buttons are part of a form and can be created with the HTML button tag.
  • Faux buttons: These are just hyperlinks styled with CSS to look like real buttons. Their purpose is to gain the user’s attention and are typically used to create what marketers term calls-to-action.

Below you can see the home page of Twitter. Neither of the two buttons are ‘real’ buttons connected to any backend server process.

The Sign up button does not sign you in to Twiiter. And the Log in button does not log you in.

Each button is just a hyperlink that leads to a different web page where you can perform that specific server-based action.

Creating your sample files

In this Tutorial, you will update a copy of a sample web page and stylesheet you created in the previous Working with Sections Tutorial.

  1. In VS Code, open the page-11.html web page in your �� websites/exercises sub-folder and save it with this new name: buttons-icons.html
  2. Open the style-11.css stylesheet in your �� websites/exercises/assets/css sub-folder and save it with this new name: buttons-icons.css
  3. In the new buttons-icons.html file, rename the linked stylesheet from style-11.css to buttons-icons.css and save the web page.
  4. Finally, in the web buttons-icons.html page, replace the current title and description details with the following:

This web page includes an image file named three-staff.jpg. You already have this in your �� websites/exercises/assets/img sub-folder.

Adding the buttons to your web page

Follow these steps to add three faux buttons to your sample buttons-icons.html web page.

  1. In VS Code, scroll to between the two text paragraphs in the second section block. This has a h2 sub-heading named “Section Heading Two” and a light-coloured background. Press the Enter key a few times to open up some empty lines.
  2. To this space, copy-and-paste the following three <p> paragraph tags, each one containing a sample hyperlink.
  3. Save the buttons-icons.html web page and view it in your browser.

You can see that the three hyperlinks appear as ‘ordinary’ hyperlinks. You have not yet created the faux button styles that will make them display as buttons.

Note that the vertical spacing between the hyperlinks is the result of the margin-bottom style rule of their surrounding <p> paragraph tags.

The <a> hyperlink tag, like the <b> bold and <i> italic tags, creates an inline element.

  • The <a> hyperlink tag does not force a line-break before or after it.
  • You cannot assign any margin value to an <a> hyperlink tag, to push other elements away from it, either vertically (above or below) or horizontally (left or right).

Creating the button styles

Next, follow the steps below to create classes with style rules for the faux buttons on your web page.

  1. In VS Code, display the buttons-icons.css stylesheet, and scroll down to the end, to just above the /* == UTILITY CLASSES === */ block.
  2. Copy-and-paste the following new classes and their style rules. You will apply this general-purpose .btn to all faux buttons, regardless of their type. (The style rules within comments are available for when you want your button text to appear in all upper-case characters.) Save your stylesheet.
  3. Switch to the buttons-icons.html web page, add the btn class to all three hyperlinks, and save the file. See below.
  4. Next, switch back to the buttons-icons.css stylesheet. Copy-and-paste the three classes below.
    • The first class ( .btn-solid ) is for when you want to style your buttons with a solid color background.
    • The second ( .btn-gradient ) is for when you want your buttons to have a colour gradient background.
    • And the third ( .btn-ghost ) is for ghost (transparent background) buttons.

    Each of the three classes has two groups of styles: one for the button’s passive state and one for its interactive state. When finished, save your buttons-icons.css stylesheet.

  5. Switch back to the buttons-icons.html web page and apply the three classes to the hyperlinks as shown below. When finished, save the web page.
  6. Display the web page in your browser. The hyperlinks-as-buttons should now look as shown below. Hover over the buttons with your mouse to view the interactive states of the buttons.

Click here to view a finished sample of this web page as it should now look.

Creating button corner styles

By default, all three button classes you created have square corners. To add some visual variety, create two more corner styles. Here are the steps.

  1. In VS Code, display the buttons-icons.css stylesheet.
  2. Under the three button-related classes you have already added, copy-and-paste these two new ones. When finished, save your stylesheet.
  3. In your web page, add the two new classes: one to the second button, and the other to the third button. See below.
  4. Save your web page and view the result in your browser. It should now look as shown below.

Click here to view a finished sample of this web page as it should now look.

Adding Font Awesome icons

Font Awesome is widely-used option for adding icons buttons on web pages. Follow the steps below to add icons from Font Awesome to your sample web page.

  1. In VS Code, display your buttons-icons.html file.
  2. In the head block, just before the closing </head> tag, copy-and-paste the following comment line and code. This adds the Font Awesome stylesheet to your web page.
  3. Use your web browser to go to this web address: https://fontawesome.com/
  4. Click the option named Icons in the menu bar across the top of the screen.
  5. On the next page displayed, you can use the Search box to locate icons by name from the Font Awesome range of 1,535+ free icons. For example, in the Search box, enter the word: user and click the result displayed below.
  6. On the next screen displayed, you can see the HTML code to generate the ‘user’ icon. Just click once on the code to copy it. The HTML icon code will look as follows.
  7. You can now copy-and-paste this or other selected icons to your web pages.
  8. In your buttons-icons.html web page, locate the second of the three hyperlink buttons.
  9. Click just before the ‘Sign Up’ text, paste the HTML code you copied from Font Awesome, and then press the Spacebar key just after the icon code.
  10. Save and view your buttons-icons.html. Your second of three button-styled hyperlinks should look similar to the following.
  11. Next, return to Font Awesome, and search for the following icon: shopping cart
  12. From the list of search results displayed, click the first one. .
  13. On the next screen displayed, click the HTML code to copy it. .
  14. In your buttons-icons.html web page, locate the first of your three hyperlink buttons.
  15. Click just before the ‘Order Now’ text, paste the HTML code you copied from Font Awesome, and then press the Spacebar key once after the pasted code.
  16. Next, return to Font Awesome, and search for the following icon: right arrow
  17. Click to select one of the options returned. For example, this one. .
  18. Copy-and-paste the icon code to just before the text of your third hyperlink button, and then press the Spacebar key once.
  19. Save and view your buttons-icons.html file. Your three button-styled hyperlinks should look similar to the following.

You have now successfully added Font Awesome icons to your web page.

Click here to view a finished sample of this web page as it should now look.

Adding spacing to icons in your buttons

Within your hyperlink buttons, the single space between the text and the icons, created by pressing the Spacebar key once, is not enough. More spacing is needed.

You could type several spaces simply by pressing the Spacebar multiple times. But the web browser will combine multiple empty spaces into a single space. So that is not a solution.

One option is to type the special HTML code that forces an empty space. This is the non-breaking space character. You type this as follows:

For example, in your first hyperlink button, you could type three non-breaking space characters before your button text as shown below.

Inside each button, between the icon code and the text, you have four spaces.

  • One space is the result of pressing the Spacebar .
  • The other three are created by the three &nbsp; character codes.

Your button will now display as follows in your web browser.

Unfortunately, adding lots of &nbsp; codes to text can cause problems when your web page is displayed on mobile-sized screens.

The better solution is to use CSS to add a margin-right spacing value to your icons. Here are the steps.

  1. In your buttons-icons.html web page, remove any &nbsp; codes you may have added inside your hyperlink buttons. You can leave the single, blank space you typed by pressing the Spacebar key.
  2. Switch to your buttons-icons.css stylesheet, and copy-and-paste the following after all your other button styles.
  3. Save your web page and stylesheet. Your web page should now look as follows.

That’s it. You have now successfully added spacing to icons within your button-styled hyperlinks.

Click buttons-icons.html to view a finished sample of this web page in a new tab of your web browser.

Positioning buttons

In the sample web page, your three buttons all appear on different lines, with some vertical space separating them. This is because each button is wrapped in a <p> tag with a margin-bottom value set in the stylesheet.

To control the spacing around and between buttons, you can enclose them in a flexbox-based div container. Here are the steps.

  1. In your sample web page, replace all three buttons by copy-and-pasting the followning. When finished, save your web page.
  2. In your stylsheet, at the top of the block that contains your button classes, copy-and-paste the new class below. When finished, save your stylesheet.
  3. View the result in your web browser, on both non-mobile and mobile viewports. Your web page should now look as shown below.
  4. To centre-align your buttons on non-mobile screens, uncomment the line below.
  5. To centre-align your buttons on mobile screens, uncomment the line below.

Even if adding just a single faux button to a web page, always enclose the button inside a container-btn tag.

✅ That’s it. You have now successfully completed this Tutorial.

Click here to view a finished sample of this web page in a new tab of your web browser.

Updating your website home page

Now that you have updated and styled a new web page, let’s add a hyperlink to it on the ‘home page’ of your web site. Follow the steps below:

  1. In VS Code, open this HTML file in your ‘main’ websites folder: index.html
  2. Copy-and-paste the following new line to your web page at end of the current list of web pages.

Save your index.html web page and view the result in your browser.

Uploading your files to GitHub

After finishing your web page and stylesheet, you are now ready to upload them to your account on GitHub.

  1. Open a new tab in your web browser and go to GitHub.com. If you are not already signed in to your GitHub account, sign in now. github-signin
  2. On your GitHub home page, click the ‘repo’ that holds your web pages. Its name will look as follows, where username is your chosen username on GitHub. username.github.iogithub-signin
  3. On the next GitHub screen displayed, near the right of the screen, you can see a button named Add file. Click on it. github-upload-portfolio
  4. From the dropdown list displayed, choose the option Upload files. Project Animation Google Fonts
  5. In File Explorer (Windows 10) or Finder (Apple Mac), drag-and-drop your index.html file and your �� exercises sub-folder to upload them to your repository on GitHub. Introduction to HTML
  6. Scroll down to the bottom of the GitHub screen, and accept or edit the short message ( Add files via upload ) in the Commit changes box.
  7. Finally, click the green Commit changes button to upload your files. Project Animation Google Fonts

Your updated home page and sample web page are now published on GitHub at web addresses similar to the following:

https://username.github.io/index.html
https://username.github.io/exercises/buttons-icons.html

It may take a few minutes for your uploaded files to appear on GitHub.

Site Map
Web Design Course

An online course that covers the fundamentals of modern web design with HTML5 and CSS3. Developed and delivered by Brendan Munnelly.

Как делается в css кнопка картинка?

Сегодня потихоньку исчезает мода на графику. Но все же по-прежнему может быть необходимость знать, как делается в css кнопка картинка? И сегодня я вам расскажу, как такую сделать.

Покажу я на примере формы подписки. Но для начала само изображение кнопки. Я выбрал вот такую милую иконочку:
arrow-right1
А вот так она выглядит непосредственно в форме подписки, пусть и самой простой:
форма подписки + кнопка картинка

При нажатии на эту кнопку произойдет отправка формы. Так как ее сделать? Очень просто, вот весь код формы:

<input type = "text" placeholder = "Введите свой e-mail">
<input type = "image" src = "arrow-right1.png">

Конечно, по-хорошему, чтобы все работало, эти поля нужно обернуть в форму, а самой форме задать обязательные атрибуты action и method . Но мы сейчас не о программировании и отправке данных на сервер, а о том, как сделать кнопку картинку.

Как видите из этого кода, это делается с помощью атрибута type = «image» . При этом такая кнопка выполняет такую же функцию, что и type = «submit» — отправляет данные формы на сервер. Вторым атрибутом выступает src — путь к картинке, которая и будет нашей кнопкой.

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

Будет работать только при выравнивании относительно одной строчки. Отлично, мы разобрались, как сделать кнопку картинку отправки формы. Но, что, если при нажатии на картинку должно происходить что-то другое? Для таких целей стоит воспользоваться другим методом, о котором я сейчас расскажу.

Создаем кнопки для любых целей, любого оформления!

По сути, практически любой парный тег годится для того, чтобы стать кнопкой. Почему? Потому что внутрь вы можете вложить картинку (или задать ее через фон), а чтобы при наведении на картинку курсор менялся на ладошку, есть css-свойство:
cursor: pointer;

Ну а саму кликабельность кнопке вы можете придать с помощью javascript и jquery. Все зависит от того, какие действия она должна выполнять. Если вы понимаете все это, то поймете и то, что кнопку создать создать абсолютно любую.

Так что тут я даже не вижу смысла приводить какие-то примеры, потому что все очевидно. Кстати, подробнее о том, как делать ссылку-картинку я писал здесь.

Минуточку вашего внимания: Все мы хотим размещать свои сайты на надежном хостинге. Я проанализировал сотни хостингов и нашел лучший — HostIQ В сети сотни положительных отзывов о нем, средняя оценка пользователей — 4.8 из 5. Пусть вашим сайтам будет хорошо.

Как поставить кнопку на сайт — простая кнопка на сайте

кнопка на сайте

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

Тег <button>

Тег <button> это простой тег HTML, с помощью которого Вы легко создадите кнопку. Он применяется совместно с другими любыми тегами, просто все чтоб будет находится внутри тегов <button>… </button> будет находится внутри Вашей кнопки.
Вот например, Button — это кнопка, которая ведет на главную страницу сайта.

А вот код этой ссылки

Конечно, простая серая кнопка выглядит совсем не презентабельно, поэтому Вы всегда можете добавить атрибут style и задать нужные стили кнопки:

Как сделать кнопку из изображения. Кнопка — картинка

Стандартные кнопки сделанные с помощью тега <button> это безусловно хорошо и просто. Но что, если Вы хотите, чтобы кнопкой являлось нужное Вам изображение? Хотите сделать кнопку из картинки? Поверьте это тоже очень просто.

кнопка на сайт

Для начала Вам нужна сама эта картинка. Ее Вы можете сделать в Фотошопе. Но я пользуюсь замечательной программой Web Button Deluxe Maker, с помощью которой создаю кнопки на любой вкус. Вы можете скачать Web Button Deluxe Maker на моем сайте. Кнопка с помощью Web Button Deluxe maker
Сама программа очень простая и интуитивно понятна. Для того, чтобы сделать кнопку достаточно выполнить всего несколько простых шагов:

  1. Ввести текст кнопки;
  2. Отредактировать шрифт (можно и не редактировать, оставить как есть);
  3. Отредактировать размер (можно оставить как есть);
  4. Выбрать дизайн кнопки;
  5. Сохранить получившеюся кнопку

Вот и все. Кнопка с помощью Web Button Deluxe готова.

Графическая кнопка на сайте

Для того, чтобы разместить графическую кнопку (кнопку-картинку) на сайте, выбираете место на странице, где должна и вставляете следующий код:

WEBTEORETIK

alt

Когда человеку тяжело,
это часто означает,
что он идёт к успеху.

alt

  • Главная
  • О сайте
  • Карта сайта
  • Обратная связь
  • Главная
  • >>
  • Раздел >> Уроки HTML
  • >>
  • Материал >>
  • Создание кнопки в HTML

Создание кнопки в HTML

Категория: Уроки HTML Просмотров: 6775 Коментариев: 0 Дата: 2017-06-01 Добавил: admin

 Создание кнопки в HTML

После того как разобрались с еще одним элементом формы textarea мы переходим, наверное, к последнему часто используемому элементу формы – это к кнопкам. Существует пять видов кнопок для формы:

1. Кнопка для отправки формы. Это самый часто используемый вид кнопки, после нажатия, на которую происходит обращение к обработчику формы, который указан в атрибуте action=«formdata.php» и уже ему передаются данные из элементов формы.

2. Это кнопка для очистки после нажатия на которую происходит очистка всех полей (элементов) в форме. То есть все возвращается к первоначальному виду формы.

3. Третий вид кнопки это кнопка картинка. Часто бывает такое, что нужно применить кнопку необычного вида, например это кнопка типа img — изображение.

4. Четвертый вид кнопки это просто кнопка. Эта кнопка, в целом, и не относится к формам, так как она не отправляет данные и не очищает форму, это просто кнопка. Такая кнопка может использоваться в любом месте страницы и не обязательно в форме. Она используется при программировании на языке JavaScript. На такую кнопку можно повесить различные действия, которые будут происходить после нажатия на нее.

5. Пятый вид так же кнопка для отправки формы, после нажатия на которую так же происходит обращение к обработчику формы action=«formdata.php», и уже ему передаются данные из элементов формы. При условии, что такая кнопка находится внутри тегов <form> </form>

Итак, мы разберем все эти четыре вида кнопки и первое это разберем кнопку для отправки данных формы.

Создание кнопки «Отправить».

Такая кнопка создается с помощью тега <input> и обязательного атрибута type со значение submit, который и указывает, что это кнопка для отправки submit, что в переводе означает подтвердить или отправить. Так же желательно задать имя для кнопки через уже известный атрибут name=«submit», ну и конечно же, чтобы появилась какая-то надпись на кнопке используем атрибут value=«Отправить». Если все это собрать в кучку у нас получится следующий вид:

После нажатия на такую кнопку, как выше уже было написано, будет происходить обращение к обработчику формы, который находится в атрибуте action=«formdata.php». А мы переходим к следующему виду кнопки.

Создание кнопки «Очистки формы».

Кнопка для очистки полей создается, так же как и для отправки, за исключением того что нужно изменить тип кнопки в атрибуте type, указав значение reset. Остальное повторяем, задаем имя кнопки name=«reset» и чтобы появилась надпись на кнопке, используем атрибут value=«Очистить». В результате получаем:

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

Создание кнопки «Отправить в виде картинки».

Для начала, изображение вашей кнопки, помещаем в уже ранее созданную папку images, которая находится на одном уровне с файлом index.html. Создается такая кнопка все также, за исключением все того же атрибута type, указав ему значение image, указывающее тип кнопки «картинка». Только, раз это картинка то нужно указать, где она лежит. Указывается путь к картинке через атрибут src=«images/batton.png». Зададим еще имя кнопке name= «imageBatton» и вот и все. Текст для кнопки в атрибуте value не нужен, так как на кнопке уже все есть.

Нажимая на кнопку-картинку, будет также происходить обращение к обработчику action=«formdata.php» для отправки данных формы, то есть такая кнопка работает так же как и кнопка типа submit. И рассмотрим последний вид кнопки.

Создание обычной кнопки.

Такая кнопка создается также просто, как и все раннее рассмотренные, меняется только тип кнопки type=«button». Все остальное также: указываем имя для кнопки name=«button»; указываем, через атрибут value=«Кнопка», надпись, которая будет отображается на кнопке. После нажатия на такую кнопку никаких действий не происходит. Такая кнопка может использоваться как в рамках формы, так и за ее пределами. Такая кнопка часто используется в сочетании с языками JavaScript и JQery.

Создание кнопки, используя тег button.

Такая кнопка создается с помощью тега <button> </button>. Ее так же можно создать, как на базе картинки, так и в стандартном виде, указав текст кнопки. На такой кнопке можно разместить различные элементы HTML, например картинку, так же к такой кнопке можно применять определенные стили: изменить размер, цвет фона, шрифт текста и др. Такая кнопка может, размещается как внутри <form> </form> так и за ее приделами. Однако если после нажатия на такую кнопку требуется отправить данные обработчику, то такая кнопка должна обязательно находится внутри тега <form> </form>.

Вот в целом рассмотрели все виды кнопок и общая картина должны получится следующая.

Так создаются кнопки HTML. Смотрите результат в Демо. У Вас должна была получится такая же картина. А мы переходим к следующему уроку.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *