Компоненты
Содержание:
All attributes of input
| Attribute name | Values | Notes |
|---|---|---|
| step | Specifies the interval between valid values in a number-based input. | |
| required | Specifies that the input field is required; disallows form submission and alerts the user if the required field is empty. | |
| readonly | Disallows the user from editing the value of the input. | |
| placeholder | Specifies placeholder text in a text-based input. | |
| pattern | Specifies a regular expression against which to validate the value of the input. | |
| multiple | Allows the user to enter multiple values into a file upload or email input. | |
| min | Specifies a minimum value for number and date input fields. | |
| max | Specifies a maximum value for number and date input fields. | |
| list | Specifies the id of a <datalist> element which provides a list of autocomplete suggestions for the input field. | |
| height | Specifies the height of an image input. | |
| formtarget | Specifies the browsing context in which to open the response from the server after form submission. For use only on input types of «submit» or «image». | |
| formmethod | Specifies the HTTP method (GET or POST) to be used when the form data is submitted to the server. Only for use on input types of «submit» or «image». | |
| formenctype | Specifies how form data should be submitted to the server. Only for use on input types «submit» and «image». | |
| formaction | Specifies the URL for form submission. Can only be used for type=»submit» and type=»image». | |
| form | Specifies a form to which the input field belongs. | |
| autofocus | Specifies that the input field should be in focus immediately upon page load. | |
| accesskey | Defines a keyboard shortcut for the element. | |
| autocomplete | Specifies whether the browser should attempt to automatically complete the input based on user inputs to similar fields. | |
| border | Was used to specify a border on an input. Deprecated. Use CSS instead. | |
| checked | Specifies whether a checkbox or radio button form input should be checked by default. | |
| disabled | Disables the input field. | |
| maxlength | Specifies the maximum number of characters that can be entered in a text-type input. | |
| language | Was used to indicate the scripting language used for events triggered by the input. | |
| name | Specifies the name of an input element. The name and value of each input element are included in the HTTP request when the form is submitted. | |
| size | Specifies the width of the input in characters. | |
| src | Defines the source URL for an image input. | |
| type | buttoncheckboxfilehiddenimagepasswordradioresetsubmittext | Defines the input type. |
| value | Defines an initial value or default selection for an input field. |
Виды кнопок html
1. Кнопка-ссылка HTML
Кнопка со ссылкой HTML (например, кнопка наверх для сайта html или кнопка назад html) может быть создана с помощью ссылок «якорей». Обычный «якорь» имеет следующий вид:
Такой «якорь» невидим и может быть поставлен в любом месте, в котором вы считаете нужным. Для того чтобы перейти к «якорю», используется следующая команда:
<a href="#имя якоря">название кнопки</a>
Нажатие на название кнопки, моментально переводит курсор к «якорю». Допустим, нам нужно, чтобы внизу сайта стояла кнопка перехода на начало, а в начале – для перехода вниз:
<!DOCTYPE html>
<html>
<head>
<title>Якорь</title>
</head>
<body>
<form>
<a name="top"></a>
<p><a href="#end">вниз</a></p>
…
<p><a href="#top">вверх</a></p>
…
<a name="end"></a>
</form>
</body>
</html>
Выглядит это следующим образом:
2. Кнопка Submit
Кнопки типа Submit существуют для отправки информации, введённой посетителем сайта, на сервер. Например, простейшая организация ввода пароля выглядит так:
<p><input name="login"></p> <p><input type="submit"></p>
3. Кнопка Reset
Кнопки типа Reset предназначены для обновления данных форм (возврата их в первоначальное состояние). Для того чтобы создать такую кнопку, следует использовать следующий код:
<input type="reset" value="Название кнопки">
4. HTML кнопка с картинкой
В HTML кнопки можно украшать какими-либо картинками. Для этого достаточно использовать следующий код:
<input type="image" src="ссылка на картинку">"
Кнопка с картинкой и текстом:
<button> <img alt="" src="ссылка на картинку" style="vertical-align:middle" />Нажмите, чтобы посмеяться</button>
Например:
Таким образом, при создании кнопок HTML можно проявить свою выдумку: любые дизайнерские фантазии реализуются написанием достаточно простого кода.
Удачи!
Justified / Full-width Button Group:
Example
<!— Three buttons in a group —><div class=»btn-group» style=»width:100%»> <button
style=»width:33.3%»>Apple</button>
<button style=»width:33.3%»>Samsung</button> <button
style=»width:33.3%»>Sony</button></div><!—
Four buttons in a group —><div class=»btn-group» style=»width:100%»> <button
style=»width:25%»>Apple</button>
<button style=»width:25%»>Samsung</button> <button
style=»width:25%»>Sony</button> <button
style=»width:25%»>HTC</button></div>
Tip: Go to our CSS Buttons Tutorial to learn
more about how to style buttons.
❮ Previous
Next ❯
HTML Ссылки
HTML по АлфавитуHTML по КатегориямHTML Атрибуты ТеговHTML Атрибуты ГлобалHTML Атрибуты СобытийHTML ЦветаHTML ХолстыHTML Аудио / ВидеоHTML Наборы символовHTML DOCTYPEsHTML Кодирование URLHTML Языковые кодыHTML Коды странHTTP Ответы сервераHTTP МетодыPX в EM конвертерГорячие клавиши
HTML Теги
<!—>
<!DOCTYPE>
<a>
<abbr>
<acronym>
<address>
<applet>
<area>
<article>
<aside>
<audio>
<b>
<base>
<basefont>
<bdi>
<bdo>
<big>
<blockquote>
<body>
<br>
<button>
<canvas>
<caption>
<center>
<cite>
<code>
<col>
<colgroup>
<data>
<datalist>
<dd>
<del>
<details>
<dfn>
<dialog>
<dir>
<div>
<dl>
<dt>
<em>
<embed>
<fieldset>
<figcaption>
<figure>
<font>
<footer>
<form>
<frame>
<frameset>
<h1> — <h6>
<head>
<header>
<hr>
<html>
<i>
<iframe>
<img>
<input>
<ins>
<kbd>
<label>
<legend>
<li>
<link>
<main>
<map>
<mark>
<menu>
<menuitem>
<meta>
<meter>
<nav>
<noframes>
<noscript>
<object>
<ol>
<optgroup>
<option>
<output>
<p>
<param>
<picture>
<pre>
<progress>
<q>
<rp>
<rt>
<ruby>
<s>
<samp>
<script>
<section>
<select>
<small>
<source>
<span>
<strike>
<strong>
<style>
<sub>
<summary>
<sup>
<svg>
<table>
<tbody>
<td>
<template>
<textarea>
<tfoot>
<th>
<thead>
<time>
<title>
<tr>
<track>
<tt>
<u>
<ul>
<var>
<video>
<wbr>
Button Shapes
Normal
Round
Rounder
and Rounder
and Rounder
Normal
Round
Rounder
and Rounder
and Rounder
The w3-round-size classes are used to add rounded
borders to buttons:
Example
<button class=»w3-button w3-round»>Round</button>
<button class=»w3-button w3-round-large»>Rounder</button>
<button class=»w3-button w3-round-xlarge»>and Rounder</button>
<button class=»w3-button w3-round-xxlarge»>and Rounder</button>
<button class=»w3-btn w3-round»>Round</button>
<button class=»w3-btn w3-round-large»>Rounder</button>
<button class=»w3-btn w3-round-xlarge»>and Rounder</button>
<button class=»w3-btn w3-round-xxlarge»>and Rounder</button>
How to style tag?
- CSS font-style property sets the style of the font. normal | italic | oblique | initial | inherit.
- CSS font-family property specifies a prioritized list of one or more font family names and/or generic family names for the selected element.
- CSS font-size property sets the size of the font.
- CSS font-weight property defines whether the font should be bold or thick.
- CSS text-transform property controls text case and capitalization.
- CSS text-decoration property specifies the decoration added to text, and is a shorthand property for text-decoration-line, text-decoration-color, text-decoration-style.
- CSS color property describes the color of the text content and text decorations.
- CSS background-color property sets the background color of an element.
- CSS text-indent property specifies the indentation of the first line in a text block.
- CSS text-overflow property specifies how overflowed content that is not displayed should be signalled to the user.
- CSS white-space property specifies how white-space inside an element is handled.
- CSS word-break property specifies where the lines should be broken.
Как сделать кнопку в HTML?
Итак, как я уже сказал, кнопки можно добавлять при помощи трех тегов, и . Каждый из этих тегов имеет свои особенности и атрибуты и используется для разных целей.
Сделать кнопку-ссылку при помощи тега , по сути, сводится к описанию его стилей в CSS. О стилях поговорим чуть позже.
Тег используется для создания кнопок, при нажатии на которые должны происходить какие-либо действия, например отправка формы, очистка формы, открытие модального окна, загрузка изображения и т.д.
Основными атрибутами таких кнопок являются:
Тип кнопки. Это необязательный параметр, и его можно пропустить. Если кнопка находится внутри формы и атрибут type отсутствует, браузер посчитает, что тип кнопки — submit и попытается отправить форму обработчику.
Несмотря на слухи, которые ходят в интернете, о том, что тег должен располагаться только внутри тегов , на самом деле это не так 🙂 Если вдруг по какой-то причине Вам нужно или хочется поместить свою кнопку вне формы, которую она должна отправлять/сбрасывать/еще-что-то-делать, просто используйте атрибут со значением соответствующим атрибуту этой формы.
Кроме того, у тега могут быть следующие атрибуты:
- — Автоматически устанавливает фокус браузера на кнопке при загрузке страницы
- — Кнопка заблокирована и нажатие на нее не выполняет никаких действий
- (только для типа submit) — адрес обработчика формы, на который отправляются данные из формы
- (только для типа submit) — Тип отправляемых данных. Может быть , ,
- (только для типа submit) — HTTP-метод, при помощи которого пересылаются данные. Может быть или
- (только для типа submit) — Отключает автоматическую валидацию введенных данных
- (только для типа submit) — Указывает на то, как выводится результат обработки формы. Может быть , , , или значение атрибута фрейма
- — Имя кнопки (можно использовать если, например, в форме есть несколько кнопок, которые ее отправляют, и обработчику нужно знать, какая из них нажата)
- — Значение кнопки (смысл примерно тот же, что и с name)
Disabled Buttons
Buttons stand out with a shadow effect and the cursor turns into a hand when mousing over them.
Disabled buttons are opaque (semi-transparent) and display a «no parking sign»:
Button
Disabled
Button
Disabled
The w3-disabled class is used to create a disabled button
(if the element support the standard HTML disabled attribute, you can use the
disabled attribute instead):
Example
<a class=»w3-button w3-disabled» href=»https://www.w3schools.com»>Link Button</a>
<button class=»w3-button» disabled>Button</button>
<input type=»button» class=»w3-button» value=»Button» disabled>
<a class=»w3-btn w3-disabled» href=»https://www.w3schools.com»>Link Button</a>
<button class=»w3-btn» disabled>Button</button>
<input type=»button» class=»w3-btn» value=»Button» disabled>
Что случится, если вместо ссылки сделать кнопку
Если URL-адрес обернуть не , а тегом , то при нажатии пользователя на правую кнопку мыши браузер предложит выполнить действия, которые положены при клике на кнопку. Адрес нельзя будет открыть в новой вкладке или отправить через контекстное меню.

Контекстное меню при клике правой кнопкой мыши на кнопку
Такая кнопка не позволит открыть страницу в новой вкладке и через комбинацию клавиш — Ctrl и левая кнопка мыши.
При наведении курсора на правильную ссылку её адрес появляется внизу окна браузера. URL-адрес, обёрнутый в <button>, не отобразится.
Адрес правильной ссылки в окне браузера при наведении на неё курсора
Еще примеры
Пример
Используйте CSS для стилизации кнопок:
<!DOCTYPE html><html><head><style>.button {
border: none; color: white; padding: 15px 32px;
text-align: center; text-decoration: none; display:
inline-block; font-size: 16px; margin: 4px 2px;
cursor: pointer;}.button1 {background-color:
#4CAF50;} /* Зеленый */.button2 {background-color: #008CBA;} /* Синий */
</style></head><body><button class=»button
button1″>Зеленый</button><button class=»button button2″>Синий</button></body></html>
Пример
Используйте CSS для стилизации кнопок (с эффектом наведения курсора мыши):
<!DOCTYPE html><html><head><style>.button {
border: none; color: white; padding: 16px 32px;
text-align: center; text-decoration: none; display:
inline-block; font-size: 16px; margin: 4px 2px;
transition-duration: 0.4s; cursor: pointer;}.button1 {
background-color: white; color: black; border: 2px
solid #4CAF50;}.button1:hover { background-color: #4CAF50;
color: white;}.button2 { background-color: white; color:
black; border: 2px solid #008CBA;}.button2:hover {
background-color: #008CBA; color: white;}</style></head><body>
<button class=»button button1″>Зеленый</button><button class=»button
button2″>Синий</button></body></html>
More
Fullscreen VideoModal BoxesDelete ModalTimelineScroll IndicatorProgress BarsSkill BarRange SlidersTooltipsDisplay Element HoverPopupsCollapsibleCalendarHTML IncludesTo Do ListLoadersStar RatingUser RatingOverlay EffectContact ChipsCardsFlip CardProfile CardProduct CardAlertsCalloutNotesLabelsCirclesStyle HRCouponList GroupList Without BulletsResponsive TextCutout TextGlowing TextFixed FooterSticky ElementEqual HeightClearfixResponsive FloatsSnackbarFullscreen WindowScroll DrawingSmooth ScrollGradient Bg ScrollSticky HeaderShrink Header on ScrollPricing TableParallaxAspect RatioResponsive IframesToggle Like/DislikeToggle Hide/ShowToggle Dark ModeToggle TextToggle ClassAdd ClassRemove ClassActive ClassTree ViewRemove PropertyOffline DetectionFind Hidden ElementRedirect WebpageZoom HoverFlip BoxCenter VerticallyCenter Button in DIVTransition on HoverArrowsShapesDownload LinkFull Height ElementBrowser WindowCustom ScrollbarHide ScrollbarShow/Force ScrollbarDevice LookContenteditable BorderPlaceholder ColorText Selection ColorBullet ColorVertical LineDividersAnimate IconsCountdown TimerTypewriterComing Soon PageChat MessagesPopup Chat WindowSplit ScreenTestimonialsSection CounterQuotes SlideshowClosable List ItemsTypical Device BreakpointsDraggable HTML ElementJS Media QueriesSyntax HighlighterJS AnimationsJS String LengthJS ExponentiationJS Default ParametersGet Current URLGet Current Screen SizeGet Iframe Elements
Menus
Icon BarMenu IconAccordionTabsVertical TabsTab HeadersFull Page TabsHover TabsTop NavigationResponsive TopnavNavbar with IconsSearch MenuSearch BarFixed SidebarSide NavigationResponsive SidebarFullscreen NavigationOff-Canvas MenuHover Sidenav ButtonsSidebar with IconsHorizontal Scroll MenuVertical MenuBottom NavigationResponsive Bottom NavBottom Border Nav LinksRight Aligned Menu LinksCentered Menu LinkEqual Width Menu LinksFixed MenuSlide Down Bar on ScrollHide Navbar on ScrollShrink Navbar on ScrollSticky NavbarNavbar on ImageHover DropdownsClick DropdownsCascading DropdownDropdown in TopnavDropdown in SidenavResp Navbar DropdownSubnavigation MenuDropupMega MenuMobile MenuCurtain MenuCollapsed SidebarCollapsed SidepanelPaginationBreadcrumbsButton GroupVertical Button GroupSticky Social BarPill NavigationResponsive Header
Кнопка Submit
Для отправки данных на сервер предназначена специальная кнопка Submit. Её вид ничем не отличается от обычных кнопок, но при нажатии на нее происходит выполнение серверной программы, указанной атрибутом action элемента <form>. Эта программа, называемая еще обработчиком формы, получает данные введённые пользователем в полях формы, производит с ними необходимые манипуляции, после чего возвращает результат в виде HTML-документа. Что именно делает обработчик, зависит от автора сайта, например, подобная технология применяется при создании опросов, форумов, тестов и многих других вещей.
Синтаксис создания кнопки Submit зависит от используемого элемента <input> или <button>.
Атрибуты те же, что и у рядовых кнопок (пример 3).
Пример 3. Отправка данных на сервер
<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>Кнопка</title>
</head>
<body>
<form>
<p><input name=»login»></p>
<p><input type=»submit»></p>
</form>
</body>
</html>
Атрибут name для этого типа кнопки можно не писать. Если не указать значение value, то браузер самостоятельно добавит текст, он различается в зависимости от браузера. Так, Firefox пишет «Отправить запрос», IE — «Подача запроса», Opera и Chrome — «Отправить». Сам текст надписи никак на функционал кнопки не влияет.
Attributes
| Attribute | Value | Description |
|---|---|---|
| autofocus | autofocus | Specifies that a button should automatically get focus when the page loads |
| disabled | disabled | Specifies that a button should be disabled |
| form | form_id | Specifies which form the button belongs to |
| formaction | URL | Specifies where to send the form-data when a form is submitted. Only for type=»submit» |
| formenctype | application/x-www-form-urlencoded multipart/form-data text/plain |
Specifies how form-data should be encoded before sending it to a server. Only for type=»submit» |
| formmethod | getpost | Specifies how to send the form-data (which HTTP method to use). Only for type=»submit» |
| formnovalidate | formnovalidate | Specifies that the form-data should not be validated on submission. Only for type=»submit» |
| formtarget | _blank _self _parent _topframename |
Specifies where to display the response after submitting the form. Only for type=»submit» |
| name | name | Specifies a name for the button |
| type | button reset submit |
Specifies the type of button |
| value | text | Specifies an initial value for the button |
Всё-таки кнопка или ссылка?
Если дизайнер по каким-то причинам не отрисовал состояния вообще, то придётся руководствоваться одной логикой.
| Ссылка | Кнопка | |
| За что отвечает | Навигация, т. е. пользователь перемещается на другую часть страницы или на новую страницу. | Выполнение какой-либо функции без перехода на другую страницу — добавить в корзину, купить, отправить, проголосовать, войти и т. д. |
| Что видит пользователь |
|
|
Пример
На макете отрисована фраза «Войти». Если клик по ней должен открывать окно для ввода регистрационных данных на этой же странице, это кнопка. Если при нажатии должна открываться отдельная страница для входа, это ссылка.

HTML Reference
HTML by AlphabetHTML by CategoryHTML Browser SupportHTML AttributesHTML Global AttributesHTML EventsHTML ColorsHTML CanvasHTML Audio/VideoHTML Character SetsHTML DoctypesHTML URL EncodeHTML Language CodesHTML Country CodesHTTP MessagesHTTP MethodsPX to EM ConverterKeyboard Shortcuts
HTML Tags
<!—>
<!DOCTYPE>
<a>
<abbr>
<acronym>
<address>
<applet>
<area>
<article>
<aside>
<audio>
<b>
<base>
<basefont>
<bdi>
<bdo>
<big>
<blockquote>
<body>
<br>
<button>
<canvas>
<caption>
<center>
<cite>
<code>
<col>
<colgroup>
<data>
<datalist>
<dd>
<del>
<details>
<dfn>
<dialog>
<dir>
<div>
<dl>
<dt>
<em>
<embed>
<fieldset>
<figcaption>
<figure>
<font>
<footer>
<form>
<frame>
<frameset>
<h1> — <h6>
<head>
<header>
<hr>
<html>
<i>
<iframe>
<img>
<input>
<ins>
<kbd>
<label>
<legend>
<li>
<link>
<main>
<map>
<mark>
<meta>
<meter>
<nav>
<noframes>
<noscript>
<object>
<ol>
<optgroup>
<option>
<output>
<p>
<param>
<picture>
<pre>
<progress>
<q>
<rp>
<rt>
<ruby>
<s>
<samp>
<script>
<section>
<select>
<small>
<source>
<span>
<strike>
<strong>
<style>
<sub>
<summary>
<sup>
<svg>
<table>
<tbody>
<td>
<template>
<textarea>
<tfoot>
<th>
<thead>
<time>
<title>
<tr>
<track>
<tt>
<u>
<ul>
<var>
<video>
<wbr>
HTML Теги
<!—><!DOCTYPE><a><abbr><acronym><address><applet><area><article><aside><audio><b><base><basefont><bdi><bdo><big><blockquote><body><br><button><canvas><caption><center><cite><code><col><colgroup><data><datalist><dd><del><details><dfn><dialog><dir><div><dl><dt><em><embed><fieldset><figcaption><figure><font><footer><form><frame><frameset><h1> — <h6><head><header><hr><html><i><iframe><img><input><ins><kbd><label><legend><li><link><main><map><mark><menu><menuitem><meta><meter><nav><noframes><noscript><object><ol><optgroup><option><output><p><param><picture><pre><progress><q><rp><rt><ruby><s><samp><script><section><select><small><source><span><strike><strong><style><sub><summary><sup><svg><table><tbody><td><template><textarea><tfoot><th><thead><time><title><tr><track><tt><u><ul><var><video>
Атрибуты ¶
У тега <button> нет обязательных атрибутов, однако мы рекомендуем всегда использовать атрибут type=”button”, если тег используется в качестве обычной кнопки.
| Атрибут | Значение | Описание |
|---|---|---|
| autofocus | autofocus | Указывает браузеру, что кнопка должна получить фокус после загрузки страницы. |
| disabled | disabled | Деактивирует кнопку. (Используется в случае, когда кнопка должна стать активной после выполнения какого-либо действия.) |
| form | form_id | Указывает форму, к которой относится кнопка. Если кнопка относится к нескольким формам, то их идентификаторы (form_id) должны быть разделены пробелами. |
| formaction | URL | Задаёт адрес, куда будут пересылаться данные формы при нажатии на кнопку. (Используется только для кнопок с атрибутом type=»submit»). |
| formenctype | application/x-www-form-urlencoded multipart/form-datatext/plain | Определяет способ кодирования данных формы перед отправкой на сервер. (Используется только для кнопок с атрибутом type=»submit»). все символы кодируются перед отправкой (значение по умолчанию). символы не кодируются пробелы заменяются знаком «+», но символы не кодируются. |
| formmethod | Указывает метод HTTP запроса, который будет использован при отправке данных формы. (Используется только для кнопок с атрибутом type=»submit») | |
| get | Передает данные формы в адресной строке («имя=значение»), которые добавляются к URL страницы после вопросительного знака и разделяются между собой амперсандом (&). (http://example.ru/doc/?name=Ivan&password=vanya) | |
| post | Браузер устанавливает связь с сервером и посылает данные для обработки. | |
| formnovalidate | formnovalidate | Отменяет проверку данных формы на корректность. (Используется только для кнопок с атрибутом type=»submit»). |
| formtarget | Указывает, где показывать ответ после отправки формы. (Используется только для кнопок с атрибутом type=»submit»). | |
| blank | открывает ответ в новом окне. | |
| self | открывает ответ в текущем окне. | |
| parent | открывает ответ в родительском фрейме. | |
| top | открывает ответ во всю ширину окна. | |
| name | name | Определяет имя кнопки. |
| type | Определяет тип кнопки. | |
| button | обычная кнопка | |
| reset | кнопка, которая очищает форму от введенных данных | |
| submit | кнопка для отправки данных формы | |
| value | text | Устанавливает значение кнопки. |
Тег <button> поддерживает глобальные атрибуты и атрибуты событий.
- CSS свойство color определяет цвет контента и оформления текста.
- CSS свойство background-color устанавливает фоновый цвет элемента.
- CSS свойство text-indent указывает размер отступа первой строки в текстовом блоке.
- CSS свойство text-overflow указывает, как будет отображаться пользователю строчный текст, выходящий за границы блока.
- CSS свойство white-space указывает, как будут отображены пробелы внутри элемента.
- CSS свойство word-break указывает перенос строки.
- CSS свойство text-shadow добавляет тень к тексту.
- CSS свойство text-align-last выравнивает последнюю строку текста.
- CSS свойство line-height устанавливает межстрочный интервал.
- CSS свойство letter-spacing устанавливает расстояние между буквами/символами в тексте.
- CSS свойство word-spacing устанавливает расстояние между словами в тексте.
HTML Tags
<!—><!DOCTYPE><a><abbr><acronym><address><applet><area><article><aside><audio><b><base><basefont><bdi><bdo><big><blockquote><body><br><button><canvas><caption><center><cite><code><col><colgroup><data><datalist><dd><del><details><dfn><dialog><dir><div><dl><dt><em><embed><fieldset><figcaption><figure><font><footer><form><frame><frameset><h1> — <h6><head><header><hr><html><i><iframe><img><input><ins><kbd><label><legend><li><link><main><map><mark><meta><meter><nav><noframes><noscript><object><ol><optgroup><option><output><p><param><picture><pre><progress><q><rp><rt><ruby><s><samp><script><section><select><small><source><span><strike><strong><style><sub><summary><sup><svg><table><tbody><td><template><textarea><tfoot><th><thead><time><title><tr><track><tt><u><ul><var><video>
Examples
Basic tag usage
Here we use a standalone button (i.e. not attached to a form). We keep things simple by using JavaScript to display an alert box when the user clicks on the button.
Button Associated to a Form
Here we associate the button to a element by using the attribute (i.e. we insert the form as the value). By doing this, we don’t need to nest the element inside the element.
About Form-Associated Elements
Some HTML elements can have a «form owner». This means that the element is associated with the form and it can be used as though it was part of that form. This can be handy if you have one or more forms on a page and the element is not nested within any of them.
The following HTML elements are «form-associated elements»:
The ability to associate a form control with a form can overcome the lack of support for nested elements. Although nested elements are not supported in the HTML specification, it is possible that a script could manipulate the DOM in a way that results in nested elements. The HTML5 specification acknowledges this situation and , while warning about the non-conformance of nested elements.
Button with an Image
You can include an element inside your element to display the image on the button. You can still add text to the button, resulting in a combination of image and text.
Like this:
How To Style Text Buttons
Step 1) Add HTML:
<button class=»btn success»>Success</button><button class=»btn
info»>Info</button><button class=»btn warning»>Warning</button><button
class=»btn danger»>Danger</button><button class=»btn
default»>Default</button>
Step 2) Add CSS:
To get the «text button» look, we remove the default background color and border:
.btn { border: none; background-color: inherit; padding: 14px 28px;
font-size: 16px; cursor: pointer; display: inline-block;}/* On mouse-over */.btn:hover
{background: #eee;}.success {color: green;}.info {color:
dodgerblue;}.warning {color: orange;}.danger {color: red;}.default {color: black;}
Attributes
| Attribute | Value | Description |
|---|---|---|
| autofocus | autofocus | Specifies that a button should automatically get focus when the page loads |
| disabled | disabled | Specifies that a button should be disabled |
| form | form_id | Specifies which form the button belongs to |
| formaction | URL | Specifies where to send the form-data when a form is submitted. Only for type=»submit» |
| formenctype | application/x-www-form-urlencoded multipart/form-data text/plain |
Specifies how form-data should be encoded before sending it to a server. Only for type=»submit» |
| formmethod | getpost | Specifies how to send the form-data (which HTTP method to use). Only for type=»submit» |
| formnovalidate | formnovalidate | Specifies that the form-data should not be validated on submission. Only for type=»submit» |
| formtarget | _blank _self _parent _topframename |
Specifies where to display the response after submitting the form. Only for type=»submit» |
| name | name | Specifies a name for the button |
| type | button reset submit |
Specifies the type of button |
| value | text | Specifies an initial value for the button |
Button Object Properties
| Property | Description |
|---|---|
| autofocus | Sets or returns whether a button should automatically get focus when the page loads, or not |
| disabled | Sets or returns whether a button is disabled, or not |
| form | Returns a reference to the form that contains a button |
| formAction | Sets or returns the value of the formaction attribute of a button |
| formEnctype | Sets or returns the value of the formenctype attribute of a button |
| formMethod | Sets or returns the value of the formmethod attribute of a button |
| formNoValidate | Sets or returns whether the form-data should be validated or not, on submission |
| formTarget | Sets or returns the value of the formtarget attribute of a button |
| name | Sets or returns the value of the name attribute of a button |
| type | Sets or returns the type of a button |
| value | Sets or returns the value of the value attribute of a button |
More Examples
Example
Use CSS to style buttons:
<!DOCTYPE html><html><head><style>.button {
border: none; color: white; padding: 15px 32px;
text-align: center; text-decoration: none; display:
inline-block; font-size: 16px; margin: 4px 2px;
cursor: pointer;}.button1 {background-color:
#4CAF50;} /* Green */.button2 {background-color: #008CBA;} /* Blue */
</style></head><body><button class=»button
button1″>Green</button><button class=»button button2″>Blue</button></body></html>
Example
Use CSS to style buttons (with hover effect):
<!DOCTYPE html><html><head><style>.button {
border: none; color: white; padding: 16px 32px;
text-align: center; text-decoration: none; display:
inline-block; font-size: 16px; margin: 4px 2px;
transition-duration: 0.4s; cursor: pointer;}.button1 {
background-color: white; color: black; border: 2px
solid #4CAF50;}.button1:hover { background-color: #4CAF50;
color: white;}.button2 { background-color: white; color:
black; border: 2px solid #008CBA;}.button2:hover {
background-color: #008CBA; color: white;}</style></head><body>
<button class=»button button1″>Green</button><button class=»button
button2″>Blue</button></body></html>
Как сделать красивую кнопку в HTML и CSS?
У каждого из нас свое представление о красоте: кто-то считает красивым закат на берегу моря, а кто-то — Ниссан Жук. О вкусах, как говорится, не спорят.
В моем представлении красивая кнопка — это кнопка, которая обладает следующими качествами:
Является интерактивной (т.е. реагирует на взаимодействие с ней пользователем). Отличительной чертой кнопок, является то, что их можно нажимать, следовательно у кнопки должно быть несколько состояний: дефолтное (состояние «покоя»), нажатое и «ховер» (при наведение курсора)
Выделяется на фоне других элементов. Посетители вашего сайта в основном бегло сканируют страницу в поисках нужной им информации. Если вам нужно, чтобы они нажимали на кнопки, сделайте их максимально заметными, контрастными. Главное не перестарайтесь.
Выглядит привычно и современно. Ваши посетители постоянно взаимодействуют с интерфейсами других сайтов и приложений. Поэтому они привыкли, что кнопки выглядят именно так, а не иначе
Если, в попытке привлечь их внимание, вы будете изобретать велосипед, пользователи могут просто не понять, что это кнопка
Кроме того, тренды в дизайне интерфейсов и технологии их создания постоянно меняются, и за ними нужно успевать.
Если вы хотите узнать как сделать кнопку объемной или с эффектом «стекляшечности», как сделать картинку кнопкой и т.д. — почитайте статьи по дизайну интерфейсов за 2005-2009 гг. 🙂
Еще одним пунктом я бы добавил, расположение кнопки в привычных для посетителей местах (например, кнопки входа/регистрации в правом верхнем углу, или кнопка отправки формы под формой). Но это уже больше относится к дизайну всей страницы.
Итак, давайте для начала сделаем две обычные кнопки, одна из которых должна открывать модальное окно (кнопка-действие — ) с формой для входа, а вторая — вести на страницу регистрации (кнопка-ссылка — ). При этом обе кнопки будут выполнены в одной стилистике.
Для вывода иконок в кнопках, да и, в общем-то, везде я использую замечательный шрифт FontAwesome, а для текста — бесплатный шрифт Roboto, с которым одинаково хорошо смотрятся как кириллические, так и латинские символы.
Теперь добавим интерактивности: при наведении кнопки будут слегка подсвечиваться, а при нажатии затемняться (как бы утапливаться).
Вот и все! Две симпатичные кнопки готовы.
При наличии желания и времени можно их дополнить плавными анимированными переходами. Вот несколько примеров:
А теперь обещанный бонус для тех кто дочитал этот пост до конца.