Buttons

Attributes¶

Attributes Value Description
autofocus autofocus Specifies that the button should receive focus after loading the page.
disabled disabled Deactivates the button. (Used when the button should become active after performing some action.)
form form_id Specifies one or more forms the button belongs to. If the button has multiple forms, then their identifiers (form_id) must be separated by spaces.
formaction URL Defines the address, where the form data will be sent after clicking on the button. (Used only for the buttons with the type=»submit» attribute).
formenctype Defines how the form-data should be encoded when a form is submitted. (Used only for type=»submit»).
application/x-www-form- All symbols are encoded before a form is submitted (default value).
urlencoded Symbols are not encoded.
multipart/form-data Spaces are being replaced by the sign «+», but symbols aren’t encoded.
text/plain
formmethod Defines the method of the HTTP request, which will be used when a form is submitted (only for type=»submit»).
get Passes the form data in the address bar («name = value»), which are added to the URL of the page after the question mark and are separated by an ampersand (&). (http://example.ru/doc/?name=Ivan&password=vanya)
post The browser communicates with the server and sends the data for processing.
formnovalidate formnovalidate Specifies that the form-data should not be validated on submission (only for type=»submit»).
formtarget Specifies, where the response will be shown after the form is submitted (only for type=»submit»).
blank Opens the response in a new window.
self Opens the response in the current window.
parent Opens the response in the parent frame.
top Opens the response in the full width window.
name name Defines the button name.
type Defines the button type.
button ordinary button
reset button, that clears the form from the input data
submit button for sending form data.
value text Defines the button value.

The <button> tag also supports the Global Attributes and the Event Attributes.

How to style <button> tag?

Common properties to alter the visual weight/emphasis/size of text in <button> 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.

Coloring text in <button> tag:

  • CSS color property describes the color of the text content and text decorations.
  • CSS background-color property sets the background color of an element.

Text layout styles for <button> tag:

  • 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.

Other properties worth looking at for <button> tag:

  • CSS text-shadow property adds shadow to text.
  • CSS text-align-last property sets the alignment of the last line of the text.
  • CSS line-height property specifies the height of a line.
  • CSS letter-spacing property defines the spaces between letters/characters in a text.
  • CSS word-spacing property sets the spacing between words.

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

Active state#

To set a button’s active state simply set the component’s
prop.

Primary button Button

<>
<Button variant=»primary» size=»lg» active>
Primary button
</Button>{‘ ‘}
<Button variant=»secondary» size=»lg» active>
Button
</Button>
</>

<>

<Buttonvariant="primary"size="lg"active>
    Primary button
</Button>{' '}

<Buttonvariant="secondary"size="lg"active>
    Button
</Button>

</>

Disabled state

Make buttons look inactive by adding the prop to.

Primary button Button

<>
<Button variant=»primary» size=»lg» disabled>
Primary button
</Button>{‘ ‘}
<Button variant=»secondary» size=»lg» disabled>
Button
</Button>{‘ ‘}
<Button href=»#» variant=»secondary» size=»lg» disabled>
Link
</Button>
</>

<>

<Buttonvariant="primary"size="lg"disabled>
    Primary button
</Button>{' '}

<Buttonvariant="secondary"size="lg"disabled>
    Button
</Button>{' '}

<Buttonhref="#"variant="secondary"size="lg"disabled>
    Link
</Button>

</>

Watch out! elements don’t naturally support a
attribute. In browsers that support it this is handled with a
style but not all browsers support it
yet.

React Bootstrap will prevent any handlers from
firing regardless of the rendered element.

Выравнивание кнопки по левому или правому краю

Способы выравнивания кнопки по левому или правому краю в Bootstrap 3 и 4 показаны в нижеприведенных примерах.

<!-- Bootstrap 3 -->
<!-- 1 Способ -->
<!-- Оборачивание кнопки с помощью элемента, например, div (который должен отображаться в документе как блочный) и добления к нему класса text-left или text-right -->
<!-- Выравнивание кнопки по левому краю -->
<div class="text-left">
    <button type="button" class="btn btn-primary">Текст кнопки</button>
</div>
<!-- Выравнивание кнопки по правому краю -->
<div class="text-right">
    <button type="button" class="btn btn-primary">Текст кнопки</button>
</div>
<!-- 2 Способ -->
<!-- Изменение типа отображения кнопки на блочный и добавления к ней CSS margin-left: auto или margin-right: auto. -->
<!-- Выравнивание кнопки по левому краю -->
<button type="button" class="btn btn-primary" style="display: block; margin-right: auto;">Текст кнопки</button>
<!-- Выравнивание кнопки по правому краю -->
<button type="button" class="btn btn-primary" style="display: block; margin-left: auto;">Текст кнопки</button>
<!-- Bootstrap 4 -->
<!-- 1 Способ -->
<!-- Оборачивание кнопки с помощью элемента, например, div (который должен отображаться в документе как блочный) и добления к нему класса text-left или text-right -->
<!-- Выравнивание кнопки по левому краю -->
<div class="text-left">
    <button type="button" class="btn btn-primary">Текст кнопки</button>
</div>
<!-- Выравнивание кнопки по правому краю -->
<div class="text-right">
    <button type="button" class="btn btn-primary">Текст кнопки</button>
</div>
<!-- 2 Способ -->
<!-- Изменение типа отображения кнопки на блочный и добавления к ней CSS margin-left: auto или margin-right: auto. В Bootstrap 4 это можно выполнить с помощью классов d-block, mr-auto и ml-auto -->
<!-- Выравнивание кнопки по левому краю -->
<button type="button" class="btn btn-primary d-block mr-auto">Текст кнопки</button>
<!-- Выравнивание кнопки по правому краю -->
<button type="button" class="btn btn-primary d-block ml-auto">Текст кнопки</button>

Full-width Buttons

To create a full-width button, add the w3-block class to the button.

Full-width buttons have a width of 100%, and spans the entire width of the parent element:

Button

Button

Button

Button

Button

Button

Example

<button class=»w3-button w3-block»>Button</button>
<button class=»w3-button w3-block w3-teal»>Button</button>
<button class=»w3-button w3-block w3-red w3-left-align»>Button</button>
<button class=»w3-btn w3-block»>Button</button>
<button class=»w3-btn w3-block w3-teal»>Button</button>
<button class=»w3-btn w3-block w3-red w3-left-align»>Button</button>

Tip: Align the button text with the w3-left-align
class or the w3-right-align class.

The size of the a block can be defined using style=»width:».

Button
Button
Button

Example

<button class=»w3-button w3-block w3-black»
style=»width:30%»>Button</button>
<button class=»w3-button w3-block w3-teal» style=»width:50%»>Button</button>
<button class=»w3-button w3-block w3-red» style=»width:80%»>Button</button>

Examples#

Use any of the available button style types to quickly create a styled
button. Just modify the prop.

Primary Secondary Success Warning Danger Info Light Dark Link

<>
<Button variant=»primary»>Primary</Button>{‘ ‘}
<Button variant=»secondary»>Secondary</Button>{‘ ‘}
<Button variant=»success»>Success</Button>{‘ ‘}
<Button variant=»warning»>Warning</Button>{‘ ‘}
<Button variant=»danger»>Danger</Button> <Button variant=»info»>Info</Button>{‘ ‘}
<Button variant=»light»>Light</Button> <Button variant=»dark»>Dark</Button>{‘ ‘}
<Button variant=»link»>Link</Button>
</>

<>

<Buttonvariant="primary">Primary</Button>{' '}

<Buttonvariant="secondary">Secondary</Button>{' '}

<Buttonvariant="success">Success</Button>{' '}

<Buttonvariant="warning">Warning</Button>{' '}

<Buttonvariant="danger">Danger</Button><Buttonvariant="info">Info</Button>{' '}

<Buttonvariant="light">Light</Button><Buttonvariant="dark">Dark</Button>{' '}

<Buttonvariant="link">Link</Button>

</>

Outline buttons

For a lighter touch, Buttons also come in
variants with no background color.

Primary Secondary Success Warning Danger Info Light Dark

<>
<Button variant=»outline-primary»>Primary</Button>{‘ ‘}
<Button variant=»outline-secondary»>Secondary</Button>{‘ ‘}
<Button variant=»outline-success»>Success</Button>{‘ ‘}
<Button variant=»outline-warning»>Warning</Button>{‘ ‘}
<Button variant=»outline-danger»>Danger</Button>{‘ ‘}
<Button variant=»outline-info»>Info</Button>{‘ ‘}
<Button variant=»outline-light»>Light</Button>{‘ ‘}
<Button variant=»outline-dark»>Dark</Button>
</>

<>

<Buttonvariant="outline-primary">Primary</Button>{' '}

<Buttonvariant="outline-secondary">Secondary</Button>{' '}

<Buttonvariant="outline-success">Success</Button>{' '}

<Buttonvariant="outline-warning">Warning</Button>{' '}

<Buttonvariant="outline-danger">Danger</Button>{' '}

<Buttonvariant="outline-info">Info</Button>{' '}

<Buttonvariant="outline-light">Light</Button>{' '}

<Buttonvariant="outline-dark">Dark</Button>

</>

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 ❯

Вариант 4:

Кнопка button

.atuin-btn {
display: inline-flex;
margin: 10px;
text-decoration: none;
position: relative;
font-size: 20px;
line-height: 20px;
padding: 12px 30px;
color: #FFF;
font-weight: bold;
text-transform: uppercase;
font-family: ‘Roboto Condensed’, Тahoma, sans-serif;
background: #337AB7;
cursor: pointer;
border: 2px solid #BFE2FF;
}
.atuin-btn:hover,
.atuin-btn:active,
.atuin-btn:focus {
color: #FFF;
}
.atuin-btn:before,
.atuin-btn:after {
content: «»;
border: 4px solid transparent;
position: absolute;
width: 0;
height: 0;
box-sizing: content-box;
}
.atuin-btn:before {
top: -6px;
left: -6px;
}
.atuin-btn:after {
bottom: -6px;
right: -6px;
}
.atuin-btn:hover:before,
.atuin-btn:active:before,
.atuin-btn:focus:before {
width: calc(100% + 4px);
height: calc(100% + 4px);
border-top-color: #337AB7;
border-right-color: #337AB7;
transition: width 0.2s ease-out, height 0.2s ease-out 0.2s;
}
.atuin-btn:hover:after,
.atuin-btn:active:after,
.atuin-btn:focus:after {
width: calc(100% + 4px);
height: calc(100% + 4px);
border-bottom-color: #337AB7;
border-left-color: #337AB7;
transition: border-color 0s ease-out 0.4s, width 0.2s ease-out 0.4s, height 0.2s ease-out 0.6s;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

.atuin-btn {

displayinline-flex;

margin10px;

text-decorationnone;

positionrelative;

font-size20px;

line-height20px;

padding12px30px;

color#FFF;

font-weightbold;

text-transformuppercase;

font-family’Roboto Condensed’,Тahoma,sans-serif;

background#337AB7;

cursorpointer;

border2pxsolid#BFE2FF;

}
.atuin-btn:hover,
.atuin-btn:active,

.atuin-btn:focus {

color#FFF;

}
.atuin-btn:before,

.atuin-btn:after {

content»»;

border4pxsolidtransparent;

positionabsolute;

width;

height;

box-sizingcontent-box;

}

.atuin-btn:before {

top-6px;

left-6px;

}

.atuin-btn:after {

bottom-6px;

right-6px;

}
.atuin-btn:hover:before,
.atuin-btn:active:before,

.atuin-btn:focus:before {

widthcalc(100%+4px);

heightcalc(100%+4px);

border-top-color#337AB7;

border-right-color#337AB7;

transitionwidth0.2sease-out,height0.2sease-out0.2s;

}
.atuin-btn:hover:after,
.atuin-btn:active:after,

.atuin-btn:focus:after {

widthcalc(100%+4px);

heightcalc(100%+4px);

border-bottom-color#337AB7;

border-left-color#337AB7;

transitionborder-color0sease-out0.4s,width0.2sease-out0.4s,height0.2sease-out0.6s;

}

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

1 вариант.

<style>
/* CSS */
.btn-rounded {
    border-radius: 19px;
    padding-top: 3px;
    padding-bottom: 3px;
    padding-left: 3px;
}
</style>
...
<!-- HTML -->
<button type="button" class="btn btn-primary btn-rounded"><i class="fas fa-map text-primary rounded-circle bg-white mr-1" style="padding: 7px 6px;"></i> Map</button>

2 вариант.

<style>
/* CSS */
.btn-icon {
    padding-top: 0;
    padding-bottom: 0;
}        
.btn > .icon {
    position: relative;
    left: -.75rem;
    display: inline-block;
    padding: .375rem .75rem;
    background: rgba(0, 0, 0, 0.15);
    border-radius: .25rem 0 0 .25rem;
}
</style>
...
<!-- HTML -->
<button type="button" class="btn btn-secondary btn-icon">
    <span class="icon"><i class="fas fa-download"></i></span>Download
</button>

3 вариант.

<!-- HTML -->
<button type="button" class="btn btn-secondary">
    Download <i class="fas fa-download"></i>
</button>

Создание группы кнопок

Шаг 1) добавить HTML:

<div class=»btn-group»>  <button>Apple</button> 
<button>Samsung</button>  <button>Sony</button></div>

Шаг 2) добавить CSS:

.btn-group button {    background-color: #4CAF50; /* Green
background */    border: 1px solid green; /* Green border
*/    color: white; /* White text */    padding: 10px
24px; /* Some padding */    cursor: pointer; /*
Pointer/hand icon */    float: left; /* Float the
buttons side by side */}.btn-group button:not(:last-child) {   
border-right: none; /* Prevent double borders */}/* Clear floats (clearfix hack) */.btn-group:after {   
content: «»;    clear: both;    display:
table;}/* Add a background color on hover */.btn-group button:hover {   
background-color: #3e8e41;}

Готовый виджет кнопки для сайта

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

Подробнее

Какие преимущества можно получить, если добавить код мультикнопки на сайт?

Особенности работы мультикнопки:

Внешний вид мультикнопки:

По желанию можно добавить цвет кнопки, подобрать иконку или установить свое изображение.

Как могут использоваться кнопки?

Опытный программист поможет добавить нужные скрипты при нажатии кнопки. Это могут быть всплывающие окна, разные виджеты и другие объекты, прописанные в JavaScript.

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

Attributes

Attribute Value Description
Boolean This Boolean attribute lets you specify that the button should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form-associated element in a document can have this attribute specified. (HTML5)
Boolean This Boolean attribute indicates that the user cannot interact with the button. If this attribute is not specified, the button inherits its setting from the containing element; if there is no containing element with the attribute set, then the button is enabled.
id The value of the attribute must be the attribute of a element in the same document. If this attribute is not specified, the element must be a descendant of a element. This attribute enables you to place elements anywhere within a document, not just as descendants of their elements. (HTML5)
URI The URI of a program that processes the information submitted by the button. If specified, it overrides the attribute of the button’s form owner. (HTML5)
application/x-www-form-urlencodedmultipart/form-datatext/plain

If the button is a submit button, this attribute specifies the type of content that is used to submit the form to the server.

  • : The default value if the attribute is not specified.
  • : Use this value if you are using an element with the attribute set to .
  • : Plain text.

If this attribute is specified, it overrides the attribute of the button’s form owner. (HTML5)

postget

If the button is a submit button, this attribute specifies the HTTP method that the browser uses to submit the form.* : The data from the form is included in the body of the form and is sent to the server.

If specified, this attribute overrides the attribute of the button’s form owner. (HTML5)

Boolean If the button is a submit button, this Boolean attribute specifies that the form is not to be validated when it is submitted. If this attribute is specified, it overrides the attribute of the button’s form owner. (HTML5)
_self_blank_parent_top If the button is a submit button, this attribute is a name or keyword indicating where to display the response that is received after submitting the form. This is a browsing context name. If this attribute is specified, it overrides the attribute of the button’s form owner.* : Load the response into the same browsing context as the current one. This value is the default if the attribute is not specified.

  • : Load the response into a new unnamed browsing context.
  • : Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as .
  • : Load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same way as . (HTML5)
name The name of the button, which is submitted with the form data.
submitresetbutton

The type of the button.

  • : The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
  • : The button resets all the controls to their initial values.
  • : The button has no default behavior. It can have client-side scripts associated with the element’s events, which are triggered when the events occur.
value The initial value of the button.

HTML example:

<button type="button">
<img src="50x50Square.png" /> Click this button.
</button>

To create simpler buttons, use .

Для чего нужна эта кнопка?

Сказать откровенно, миллионы сайтов живут без подобной кнопки. Ничего критичного в её отсутствии нет, но применение этого элемента может принести определенную пользу, как для посетителей, так и для вас, как для владельца ресурса.

Польза для посетителей

Страницы сайтов нередко перегружены контентом. Длинные и подробные статьи заставляют посетителей спускаться все ниже и ниже, прокручивая текст колесиком мыши. В самом конце их ожидают еще и десятки комментариев и для того, чтобы добавить свои, им приходится проделать еще больше работы.

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

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

Польза для сайта

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

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

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

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

Adblock
detector