Как изменить цвет кнопки при наведении html

In this article you'll see how to style a button using CSS. My goal here is mostly to showcase how different CSS rules and styles are applied and used. We won't see much design inspiration nor will we discuss ideas for styling. Instead, this will be more of an overview of how the styles themselves work, what properties are commonly used, and how they can be combined. You'll first see how to create a button in HTML. Then you'll learn how to override the default styles of buttons. Lastly, you'l

CSS Button Style – Hover, Color, and Background

In this article you’ll see how to style a button using CSS.

My goal here is mostly to showcase how different CSS rules and styles are applied and used. We won’t see much design inspiration nor will we discuss ideas for styling.

Instead, this will be more of an overview of how the styles themselves work, what properties are commonly used, and how they can be combined.

You’ll first see how to create a button in HTML. Then you’ll learn how to override the default styles of buttons. Lastly, you’ll get a glimpse of how to style buttons for their three different states.

Here’s an Interactive Scrim of CSS Button Style

Table of Contents

  1. Create a button in HTML
  2. Change default styling of buttons
    1. Change the background color
    2. Change text color
    3. Change the border style
    4. Change the size
  3. Style button states
    1. Style hover state
    2. Style focus state
    3. Style active state
  4. Conclusion

Let’s get started!

How to Create a Button in HTML

To create a button, use the <button> element.

This is a more accessible and semantic option compared to using a generic container which is created with the <div> element.

In the index.html file below, I’ve created the basic structure for a webpage and added a single button:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>CSS Button Style</title>
</head>
<body>
    <button type="button" class="button">Click me!</button>
</body>
</html>

Let’s break down the line <button type="button" class="button">Click me!</button>:

  • You first add the button element, which consists of an opening <button> and closing </button> tag.
  • The type="button" attribute in the opening <button> tag explicitly creates a clickable button. Since this particular button is not used for submitting a form, it is useful for semantic reasons to add it in order to make the code clearer and not trigger any unwanted actions.
  • The class="button" attribute will be used to style the button in a separate CSS file. The value button could be any other name you choose. For example you could have used class="btn".
  • The text Click me! is the visible text inside the button.

Any styles that will be applied to the button will go inside a spearate style.css file.

You can apply the styles to the HTML content by linking the two files together. You do this with the <link rel="stylesheet" href="style.css"> tag which was used in index.html.

In the style.css file, I’ve added some styling which only centers the button in the middle of the browser window.

Notice that the class="button" is used with the .button selector. This is a way to apply styles directly to the button.

* {
    box-sizing: border-box;
} 

body {
    display:flex;
    justify-content: center;
    align-items: center;
    margin:50px auto;
}

.button {
    position: absolute;
    top:50%
}

The code from above will result in the following:

Screenshot-2022-02-06-at-10.29.02-PM

The default styling of buttons will vary depending on the browser you’re using.

This is an example of how the native styles for buttons look on the Google Chrome browser.

How to Change the Default Styling of Buttons

How to Change the Background Color of Buttons

To change the background color of the button, use the CSS background-color property and give it a value of a color of your taste.

In the .button selector, you use background-color:#0a0a23; to change the background color of the button.

.button {
    position: absolute;
    top:50%;
    background-color:#0a0a23;
}

Screenshot-2022-02-06-at-10.28.30-PM

How to Change the Text Color of Buttons

The default color of text is black, so when you add a dark background color you will notice that the text has disappeared.

Another thing to make sure of is that there is enough contrast between the button’s background color and text color. This helps make the text more readable and easy on the eyes.

Next, use the color property to change the color of text:

.button {
    position: absolute;
    top:50%;
    background-color:#0a0a23;
    color: #fff;
}

Screenshot-2022-02-06-at-10.28.03-PM

How to Change the Border Style of Buttons

Notice the grey around the edges of the button? That is the default color of the button’s borders.

One way to fix this is to use the border-color property. You set the value to be the same as the value of background-color. This makes sure the borders have the same color as the background of the button.

Another way would be to remove the border around the button entirely by using border:none;.

.button {
  position: absolute;
  top:50%;
  background-color:#0a0a23;
  color: #fff;
  border:none;
}

Screenshot-2022-02-06-at-10.27.33-PM

Next, you can also round-up the edges of the button by using the border-radius property, like so:

.button {
    position: absolute;
    top:50%;
    background-color:#0a0a23;
    color: #fff;
    border:none;
    border-radius:10px;
  }

Screenshot-2022-02-06-at-10.26.57-PM

You could also add a slight dark shadow effect around the button by using the box-shadow property:

 position: absolute;
    top:50%;
    background-color:#0a0a23;
    color: #fff;
    border:none;
    border-radius:10px;
    box-shadow: 0px 0px 2px 2px rgb(0,0,0);

Screenshot-2022-02-06-at-10.25.55-PM

How to Change the Size of Buttons

The way to create more space inside the button’s borders is to increase the padding of the button.

Below I added a value of 15px for the top, bottom, right, and left padding of the button.

I also set a minimum height and width, with the min-height and min-width properties respectively. Buttons need to be large enough for all different kind of devices.

.button {
    position: absolute;
    top:50%;
    background-color:#0a0a23;
    color: #fff;
    border:none; 
    border-radius:10px; 
    padding:15px;
    min-height:30px; 
    min-width: 120px;
  }

Screenshot-2022-02-06-at-10.42.58-PM

How to Style Button States

Buttons have three different states:

  • :hover
  • :focus
  • :active

It’s best that the three states are styled differently and don’t share the same styles.

In the following sections I’ll give a brief explanation on what each one of the states mean and what triggers them. You’ll also see some ways you can style the button for each separate state.

Here’s an interactive scrim about styling button states:

How to Style :hover States

The :hover state becomes present when a user hovers over a button, by bringing their mouse or trackpad over it, without selecting it or clicking on it.

To change the button’s styles when you hover over it, use the :hover CSS
pseudoclass selector.

A common change to make with :hover is switching the background-color of the button.

To make the change less sudden, pair :hover with the transition property.

The transition property will help make the transition from no state to a :hover state much smoother.

The change of background color will happen a bit slower than it would without the transition property. This will also help make the end result less jarring for the user.

.button:hover {
      background-color:#002ead;
      transition: 0.7s;
  }

In the example above, I used a Hex color code value to make the background color a lighter shade for when I hover over the button.

With the help of the transition property I also caused a delay of 0.7s when the transition from no state to a :hover state happens. This caused a slower transition from the original #0a0a23 background color to the #002ead background color.

hover

Keep in mind that the :hover pseudoclass does not work for mobile device screens and mobile apps. Choose to use hover effects only for desktop web applications and not touch screens.

How to Style :focus States

The :focus state takes effect for keyboard users — specifically it will activate when you focus on a button by hitting the Tab key ().

If you’re following along, when you focus on the button after pressing the Tab key, you’ll see the following:

focus-5

Notice the slight light blue outline around the button when it’s gained focus?

Browsers have default styling for the :focus pseudoclass, for accessibility keyboard navigation purposes. It’s not a good idea to remove that outline altogether.

You can however create custom styles for it and make it easily detectable.

A way to do so is by setting the outline color to first be transparent.

Following that, you can maintain the outline-style to solid. Lastly, using the box-shadow property, you can add a color of your liking for when the element is focused on:

 .button:focus {
    outline-color: transparent;
    outline-style:solid;
    box-shadow: 0 0 0 4px #5a01a7;
}

focusend

You can also again pair these styles with the transition property, depending on the effect you want to achieve:

  .button:focus {
    outline-color: transparent;
    outline-style:solid;
    box-shadow: 0 0 0 4px #5a01a7;
    transition: 0.7s;
}

focusend1

How to Style for the :active State

The :active state gets activated when you click on the button by either clicking the computer’s mouse or pressing down on the laptop’s trackpad.

That being said, look at what happens when I click the button after I’ve applied and kept the styles for the :hover and :focus states:

active-1

The :hover state styles are applied before clicking when I hover over the button.

The :focus state styles are applied also, because when a button is clicked it also gains a :focus state alongside an :active one.

However, keep in mind that they are not the same thing.

:focus state is when an element is being focused on and :active is when a user clicks on an element by holding and pressing down on it.

To change the style for when a user clicks a button, apply styles to the :active CSS pseudoselector.

In this case, I’ve changed the background color of the button when a user clicks on it

.button:active {
    background-color: #ffbf00;
}

activefinal

Conclusion

And there you have it! You now know the basics of how to style a button with CSS.

We went over how to change the background color and text color of buttons as well as how to style buttons for their different states.

To learn more about web design, check out freeCodeCamp’s Responsive Web Design Certification. In the interactive lessons, you’ll learn HTML and CSS by building 15 practice projects and 5 certification projects.

Note that the above cert is still in beta — if you want the latest stable version, check here.

Thanks for reading and happy coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

CSS Button Style – Hover, Color, and Background

In this article you’ll see how to style a button using CSS.

My goal here is mostly to showcase how different CSS rules and styles are applied and used. We won’t see much design inspiration nor will we discuss ideas for styling.

Instead, this will be more of an overview of how the styles themselves work, what properties are commonly used, and how they can be combined.

You’ll first see how to create a button in HTML. Then you’ll learn how to override the default styles of buttons. Lastly, you’ll get a glimpse of how to style buttons for their three different states.

Here’s an Interactive Scrim of CSS Button Style

Table of Contents

  1. Create a button in HTML
  2. Change default styling of buttons
    1. Change the background color
    2. Change text color
    3. Change the border style
    4. Change the size
  3. Style button states
    1. Style hover state
    2. Style focus state
    3. Style active state
  4. Conclusion

Let’s get started!

How to Create a Button in HTML

To create a button, use the <button> element.

This is a more accessible and semantic option compared to using a generic container which is created with the <div> element.

In the index.html file below, I’ve created the basic structure for a webpage and added a single button:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>CSS Button Style</title>
</head>
<body>
    <button type="button" class="button">Click me!</button>
</body>
</html>

Let’s break down the line <button type="button" class="button">Click me!</button>:

  • You first add the button element, which consists of an opening <button> and closing </button> tag.
  • The type="button" attribute in the opening <button> tag explicitly creates a clickable button. Since this particular button is not used for submitting a form, it is useful for semantic reasons to add it in order to make the code clearer and not trigger any unwanted actions.
  • The class="button" attribute will be used to style the button in a separate CSS file. The value button could be any other name you choose. For example you could have used class="btn".
  • The text Click me! is the visible text inside the button.

Any styles that will be applied to the button will go inside a spearate style.css file.

You can apply the styles to the HTML content by linking the two files together. You do this with the <link rel="stylesheet" href="style.css"> tag which was used in index.html.

In the style.css file, I’ve added some styling which only centers the button in the middle of the browser window.

Notice that the class="button" is used with the .button selector. This is a way to apply styles directly to the button.

* {
    box-sizing: border-box;
} 

body {
    display:flex;
    justify-content: center;
    align-items: center;
    margin:50px auto;
}

.button {
    position: absolute;
    top:50%
}

The code from above will result in the following:

Screenshot-2022-02-06-at-10.29.02-PM

The default styling of buttons will vary depending on the browser you’re using.

This is an example of how the native styles for buttons look on the Google Chrome browser.

How to Change the Default Styling of Buttons

How to Change the Background Color of Buttons

To change the background color of the button, use the CSS background-color property and give it a value of a color of your taste.

In the .button selector, you use background-color:#0a0a23; to change the background color of the button.

.button {
    position: absolute;
    top:50%;
    background-color:#0a0a23;
}

Screenshot-2022-02-06-at-10.28.30-PM

How to Change the Text Color of Buttons

The default color of text is black, so when you add a dark background color you will notice that the text has disappeared.

Another thing to make sure of is that there is enough contrast between the button’s background color and text color. This helps make the text more readable and easy on the eyes.

Next, use the color property to change the color of text:

.button {
    position: absolute;
    top:50%;
    background-color:#0a0a23;
    color: #fff;
}

Screenshot-2022-02-06-at-10.28.03-PM

How to Change the Border Style of Buttons

Notice the grey around the edges of the button? That is the default color of the button’s borders.

One way to fix this is to use the border-color property. You set the value to be the same as the value of background-color. This makes sure the borders have the same color as the background of the button.

Another way would be to remove the border around the button entirely by using border:none;.

.button {
  position: absolute;
  top:50%;
  background-color:#0a0a23;
  color: #fff;
  border:none;
}

Screenshot-2022-02-06-at-10.27.33-PM

Next, you can also round-up the edges of the button by using the border-radius property, like so:

.button {
    position: absolute;
    top:50%;
    background-color:#0a0a23;
    color: #fff;
    border:none;
    border-radius:10px;
  }

Screenshot-2022-02-06-at-10.26.57-PM

You could also add a slight dark shadow effect around the button by using the box-shadow property:

 position: absolute;
    top:50%;
    background-color:#0a0a23;
    color: #fff;
    border:none;
    border-radius:10px;
    box-shadow: 0px 0px 2px 2px rgb(0,0,0);

Screenshot-2022-02-06-at-10.25.55-PM

How to Change the Size of Buttons

The way to create more space inside the button’s borders is to increase the padding of the button.

Below I added a value of 15px for the top, bottom, right, and left padding of the button.

I also set a minimum height and width, with the min-height and min-width properties respectively. Buttons need to be large enough for all different kind of devices.

.button {
    position: absolute;
    top:50%;
    background-color:#0a0a23;
    color: #fff;
    border:none; 
    border-radius:10px; 
    padding:15px;
    min-height:30px; 
    min-width: 120px;
  }

Screenshot-2022-02-06-at-10.42.58-PM

How to Style Button States

Buttons have three different states:

  • :hover
  • :focus
  • :active

It’s best that the three states are styled differently and don’t share the same styles.

In the following sections I’ll give a brief explanation on what each one of the states mean and what triggers them. You’ll also see some ways you can style the button for each separate state.

Here’s an interactive scrim about styling button states:

How to Style :hover States

The :hover state becomes present when a user hovers over a button, by bringing their mouse or trackpad over it, without selecting it or clicking on it.

To change the button’s styles when you hover over it, use the :hover CSS
pseudoclass selector.

A common change to make with :hover is switching the background-color of the button.

To make the change less sudden, pair :hover with the transition property.

The transition property will help make the transition from no state to a :hover state much smoother.

The change of background color will happen a bit slower than it would without the transition property. This will also help make the end result less jarring for the user.

.button:hover {
      background-color:#002ead;
      transition: 0.7s;
  }

In the example above, I used a Hex color code value to make the background color a lighter shade for when I hover over the button.

With the help of the transition property I also caused a delay of 0.7s when the transition from no state to a :hover state happens. This caused a slower transition from the original #0a0a23 background color to the #002ead background color.

hover

Keep in mind that the :hover pseudoclass does not work for mobile device screens and mobile apps. Choose to use hover effects only for desktop web applications and not touch screens.

How to Style :focus States

The :focus state takes effect for keyboard users — specifically it will activate when you focus on a button by hitting the Tab key ().

If you’re following along, when you focus on the button after pressing the Tab key, you’ll see the following:

focus-5

Notice the slight light blue outline around the button when it’s gained focus?

Browsers have default styling for the :focus pseudoclass, for accessibility keyboard navigation purposes. It’s not a good idea to remove that outline altogether.

You can however create custom styles for it and make it easily detectable.

A way to do so is by setting the outline color to first be transparent.

Following that, you can maintain the outline-style to solid. Lastly, using the box-shadow property, you can add a color of your liking for when the element is focused on:

 .button:focus {
    outline-color: transparent;
    outline-style:solid;
    box-shadow: 0 0 0 4px #5a01a7;
}

focusend

You can also again pair these styles with the transition property, depending on the effect you want to achieve:

  .button:focus {
    outline-color: transparent;
    outline-style:solid;
    box-shadow: 0 0 0 4px #5a01a7;
    transition: 0.7s;
}

focusend1

How to Style for the :active State

The :active state gets activated when you click on the button by either clicking the computer’s mouse or pressing down on the laptop’s trackpad.

That being said, look at what happens when I click the button after I’ve applied and kept the styles for the :hover and :focus states:

active-1

The :hover state styles are applied before clicking when I hover over the button.

The :focus state styles are applied also, because when a button is clicked it also gains a :focus state alongside an :active one.

However, keep in mind that they are not the same thing.

:focus state is when an element is being focused on and :active is when a user clicks on an element by holding and pressing down on it.

To change the style for when a user clicks a button, apply styles to the :active CSS pseudoselector.

In this case, I’ve changed the background color of the button when a user clicks on it

.button:active {
    background-color: #ffbf00;
}

activefinal

Conclusion

And there you have it! You now know the basics of how to style a button with CSS.

We went over how to change the background color and text color of buttons as well as how to style buttons for their different states.

To learn more about web design, check out freeCodeCamp’s Responsive Web Design Certification. In the interactive lessons, you’ll learn HTML and CSS by building 15 practice projects and 5 certification projects.

Note that the above cert is still in beta — if you want the latest stable version, check here.

Thanks for reading and happy coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

I need to change the color of a button on hover.

Here is my solution, but it doesn’t work.

a.button {
   display: -moz-inline-stack;
   display: inline-block;
   width: 391px;
   height: 62px;
   background: url("img/btncolor.png") no-repeat;
   line-height: 62px;
   vertical-align: text-middle;
   text-align: center;
   color: #ebe6eb;
   font-family: Zenhei;
   font-size: 39px;
   font-weight: normal;
   font-style: normal;
   text-shadow: #222222 1px 1px 0;
}
a.button a:hover{
     background: #383;
}

freedomn-m's user avatar

freedomn-m

26.8k8 gold badges34 silver badges55 bronze badges

asked Oct 10, 2010 at 2:37

getaway's user avatar

a.button a:hover means «a link that’s being hovered over that is a child of a link with the class button«.

Go instead for a.button:hover.

answered Oct 10, 2010 at 2:39

Matchu's user avatar

MatchuMatchu

82.8k18 gold badges152 silver badges160 bronze badges

0

Seems your selector is wrong, try using:

a.button:hover{
     background: #383;
}

Your code

a.button a:hover

Means it is going to search for an a element inside a with class button.

answered Oct 10, 2010 at 2:40

BrunoLM's user avatar

BrunoLMBrunoLM

96.4k82 gold badges297 silver badges449 bronze badges

a.button:hover{
    background: #383;  }

works for me but in my case

#buttonClick:hover {
background-color:green;  }

answered May 25, 2016 at 12:56

Penh's user avatar

🗓️ Обновлено: 30.01.2022

💬Комментариев:
0

👁️Просмотров: 7050

Поменяем цвет фона и текста у кнопки при наведении.

Будем использовать два способа. Первый — просто меняем фон и цвет у кнопки. Второй — меняем фон кнопки с помощью псевдоэлемента :before

Кнопка внутри формы (button type=»submit»)

Просто меняем фон и цвет:

See the Pen
#1 Просто меняем фон и цвет кнопки — button type=»submit» by Pelegrin (@pelegrin2puk)
on CodePen.

Меняем через псевдоэлемент :before (обратите внимание на span, который нужно разместить внутри кнопки):

See the Pen
Меняем фон с помощью :before — button type=»submit» by Pelegrin (@pelegrin2puk)
on CodePen.

Кнопка внутри формы (input type=»submit»):

Тот же самый принцип, что и выше, но вместо button[type=»submit»] нужно в css прописать input[type=»submit»]

Кнопка, как отдельный элемент в html кода:

Просто меняем фон и цвет:

See the Pen
Изменить цвет кнопки — обычный div by Pelegrin (@pelegrin2puk)
on CodePen.

А теперь меняем цвет, с помощью псевдоэлемента :before

See the Pen
Изменить цвет кнопки с помощью :before — обычный div by Pelegrin (@pelegrin2puk)
on CodePen.

Кнопка в Bootstrap

Чтобы изменить цвет кнопки в Bootstrap, вам необходимо найти нужный класс (или id), а также нужный порядок вложенности элементов.

К примеру, у вас есть кнопка

<button type="button" class="btn btn-outline-primary">Primary</button>

И вы хотите изменить для нее цвет при наведении. Тогда я бы рекомендовал в css прописать следующее:

.btn.btn-outline-primary:hover {
  background: red; /* Либо любой другой цвет */
  /* А также заменил бы цвет и для border */
}

Как изменить цвет кнопки с помощью Js

Я покажу два варианта, как поменять цвет кнопки при наведении используя JavaScript.

Первый вариант — мы будем добавлять класс с нашей кнопки через js:

See the Pen
YzWmEGX by Pelegrin (@pelegrin2puk)
on CodePen.

Второй вариант — мы будем менять css стили прямо в js:

See the Pen
#2 Меняем цвет кнопки c помощью JS — меняем стили внутри JavaScript by Pelegrin (@pelegrin2puk)
on CodePen.

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

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

1. Как оживить кнопку

Очень советуем не просто читать туториал, а выполнять его вместе с нами, шаг за шагом. Так материал быстрее усвоится и повторить его будет проще.

1.1. Запустите стартовый шаблон

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

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <style type="text/css">
      .animated-btn {
        background-color: red;
      }
    </style>
  </head>
  <body>
    <button class="animated-btn">Кнопка</button>
  </body>
</html>

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

1.2. Добавьте класс с новым стилем

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

Сейчас создайте второе CSS-правило для той же кнопки. Поместите новое правило ниже первого.

.animated-btn {
  background-color: red;
}
.animated-btn {
  background-color: blue;
}

Откройте Инструменты разработчика браузера, и вы увидите, что оба правила сработали. Оба правила меняют стиль background-color и поэтому второе перекрыло первое:

Кнопка стала синего цвета. Теперь научите её реагировать на движение мыши.

1.3. Добавьте :hover

Теперь дело за малым: добавьте новому селектору ключевое слово :hover. Да, вот так просто:

.animated-btn {
  background-color: red;
}
.animated-btn:hover {
  background-color: blue;
}

Теперь кнопка меняет цвет при наведении:

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

Правило .animated-btn:hover говорит браузеру: Ищу тег с классом animated-btn, и чтобы на него смотрел указатель мыши. Когда мышь наведена на кнопку, то правило срабатывает. Как только мышь перемещается на другой тег — перестаёт.

Псевдокласс :hover появляется и исчезает при движении мыши

Есть ещё одна особенность у :hover. Псевдокласс получает не только один тег, но все его родители. В примере с кнопкой это будут сразу два тега <button> и <body>:

...
<body>
    <button class="animated-btn">Кнопка</button>
...

1.4. Добавьте больше стилей

Очевидно, что вместо смены цвета вы могли поменять кнопку как угодно. Например, добавить ей тень:

2. Как расширить область hover

Менять кнопку при наведении вы научились. А что, если вы хотите менять кнопку по наведению мыши на тег рядом с ней?

2.1. Запустите стартовый шаблон

Используйте наш стартовый шаблон, это красная кнопка внутри зелёного квадрата:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <style type="text/css">
      .animated-btn {
          background-color: red;
      }
      .btn-wrapper {
          height: 100px;
          width: 100px;
          background-color: green;
          display: flex;
          align-items: center;
          justify-content: center;
      }
    </style>
  </head>
  <body>
    <div class="btn-wrapper">
      <button class="animated-btn">Кнопка</button>
    </div>
  </body>
</html>

Выглядит это примерно так:

2.2. Добавьте класс с новым стилем

Давайте сделаем кнопку синей. Но, на этот раз, при написании селектора сперва, выберите зелёный контейнер, а уже потом кнопку внутри него. Добавьте такое правило:

.btn-wrapper .animated-btn {
    background-color: blue;
}

Результат:

2.3. Добавьте :hover

На этот раз :hover должен достаться селектору для зелёного прямоугольника:

.btn-wrapper:hover .animated-btn {
    background-color: blue;
}

Понять как работает селектор можно, прочитав его задом наперёд: Найди элемент с классом animated-btn, да такой, чтобы среди родителей у него был элемент с классом btn-wrapper и мышь была наведена на этого родителя. Вот как это выглядит в действии:

3. Что делать, если не получилось

Бывает такое, что пишешь анимацию, а она всё равно не работает. И что делать?

3.1. Проверьте, что один элемент внутри другого

Зайдите в Chrome Dev Tools и найдите элемент, к которому подключаете анимацию. Он точно внутри нужного тега?

3.2. Проверьте селектор

На вкладке Elements в Chrome Dev Tools нажмите комбинацию клавиш Ctrl+F. Откроется поле для поиска тегов. Вбейте туда свой селектор и нажмите Enter. Нужный тег должен подсветиться жёлтым цветом. Если этого не произошло, то ваш селектор написан неправильно.

3.3. Проверьте стили

Возможно ваш стиль просто не работает. Уберите :hover и проверьте, что стиль срабатывает правильно хотя бы без анимации.

Читать дальше

  • Какие существуют псевдоклассы
  • Полный список псевдоклассов на MDN (en)
  • Специфичность селекторов

Узнайте, как стиль кнопок с помощью CSS.


Основные стили кнопок

Пример

.button {
    background-color: #4CAF50; /* Green */
    border: none;
   
color: white;
    padding: 15px 32px;
    text-align: center;
   
text-decoration: none;
    display: inline-block;
    font-size: 16px;
}


Цвета кнопок

Используйте свойство background-color для изменения цвета фона кнопки:

Пример

.button1 {background-color: #4CAF50;} /* Green */
.button2
{background-color: #008CBA;} /* Blue */
.button3 {background-color:
#f44336;} /* Red */
.button4 {background-color: #e7e7e7; color: black;} /* Gray */
.button5
{background-color: #555555;} /* Black */



Размеры кнопок

Используйте свойство font-size для изменения размера шрифта кнопки:

Пример

.button1 {font-size: 10px;}
.button2 {font-size: 12px;}
.button3
{font-size: 16px;}
.button4 {font-size: 20px;}
.button5 {font-size: 24px;}

Используйте свойство padding для изменения заполнения кнопки:

Пример

.button1 {padding: 10px
24px;}
.button2 {padding: 12px 28px;}
.button3 {padding: 14px 40px;}
.button4 {padding: 32px 16px;}
.button5 {padding: 16px;}


Закругленные кнопки

Используйте свойство border-radius для добавления скругленных углов к кнопке:

Пример

.button1 {border-radius: 2px;}
.button2 {border-radius: 4px;}
.button3
{border-radius: 8px;}
.button4 {border-radius: 12px;}
.button5 {border-radius: 50%;}


Цветные границы кнопок

Используйте свойство border, чтобы добавить цветную рамку к кнопке:

Пример

.button1 {
    background-color: white;
    color: black;
   
border: 2px solid #4CAF50; /* Green */
}


Наведите кнопки

Используйте селектор :hover для изменения стиля кнопки при наведении на нее указателя мыши.

Совет: Используйте свойство transition-duration для определения скорости эффекта «Hover»:

Пример

.button {
    -webkit-transition-duration: 0.4s; /* Safari */
   
transition-duration: 0.4s;
}

.button:hover {
   
background-color: #4CAF50; /* Green */
    color: white;
}


Кнопки теней

Use the box-shadow property to add shadows to a button:

Пример

.button1 {
    box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0
rgba(0,0,0,0.19);
}

.button2:hover {
    box-shadow: 0 12px
16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
}


Отключенные кнопки

Используйте свойство opacity для добавления прозрачности к кнопке (создает «отключенный» вид).

Совет: Вы также можете добавить свойство cursor со значением «not-allowed», которое будет отображать «нет парковки знак» при наведении указателя мыши на кнопку:

Пример

.disabled {
    opacity: 0.6;
    cursor: not-allowed;
}


Ширина кнопки

По умолчанию размер кнопки определяется по ее текстовому содержимому (так же широко, как и ее содержимое). Используйте свойство width для изменения ширины кнопки:

Пример

.button1 {width: 250px;}
.button2 {width: 50%;}
.button3 {width:
100%;}


Группы кнопок

Удалите поля и добавьте float:left к каждой кнопке, чтобы создать группу кнопок:

Пример

.button {
    float: left;
}


Группа кнопок на границе

Используйте свойство border для создания группы кнопок с рамками:

Пример

.button {
    float: left;
    border: 1px
solid green;
}


Вертикальная группа кнопок

Используйте display:block вместо float:left для группирования кнопок ниже друг друга, вместо того, чтобы бок о бок:

Пример

.button {
    display: block;
}


Кнопка на картинке

Snow


Анимированные кнопки

Пример

Добавить стрелку на наведении:

Пример

Добавить «нажатия» эффект на кнопку:

Пример

Исчезать при наведении:

Пример

Добавить эффект «рябь» при щелчке:

Три эффекта наведения на кнопку

Три эффекта наведения на кнопку

На этом уроке мы разберем три разных эффекта при наведении на кнопку.

Посмотрите демо на CodePen

HTML разметка

Создадим в разметке три разных блока и и обернем в контейнер с классом wrapper для выравнивания их по центру. Один блок — одна кнопка.


<div class="wrapper">
    <div class="buttonLeft"><span>Left</span></div>
    <div class="buttonOverlay"><span>Center</span></div>
    <div class="pressDown"><span>Right</span></div>
</div>

Замена цвета кнопки при наведении (эффект 1)

Создадим кнопку слева.


.buttonLeft {
    border-radius: 5px; // скругление
    padding: 0 40px; //поля внутри кнопки
    overflow: hidden; // скрыть все что выходит за родителя
    background: #BA7BA1; // цвет кнопки
    position: relative; // установим позицию родителя
    line-height: 40px;
    color: #fff; // цвет текста
    margin-right: 40px; // промежуток между кнопками
}

В качестве заполнения кнопки другим цветом, будет служить псевдоэлемент before. Однако увидеть, как происходит плавная замена одного цвета на другой, можно будет только при наведении на кнопку. Весь фокус состоит в трансформации псевдоэлемента before: из невидимой (-100%) позиции в состоянии покоя в видимую (0) при наведении.


.buttonLeft::before {
    content: '';
    position: absolute; // позиционировать относительно родителя
    left: 0; // координата псевдоэлемента
    bottom: 0;
    width: 100%;
    height: 100%;
    transform: translateX(-100%); // прячем псевдоэлемент за родителем
    background: #EC008C; // новый цвет
    transition: transform .2s ease-in-out; // плавная анимация
}

.buttonLeft:hover::before {
    transform: translateX(0); // показываем псевдоэлемент
}

.buttonLeft span {
    position: relative;
    z-index: 1; // текст сверху
}

Три эффекта наведения на кнопку.

Изменение положения кнопки при наведении (эффект 2)

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


// задаем позиционирование
.buttonOverlay {
    padding: 10px 25px;
    position: relative;
    color: #fff;
    margin-right: 40px;
}

// рисуем выпавшую кнопку
.buttonOverlay::before {
    content: '';
    position: absolute;
    border-radius: 5px;
    height: 100%;
    width: 100%;
    top: 5px;
    right: 5px;
    background-color: #BA7BA1;
    z-index: -1;
    transition: transform .2s ease-in-out;
}

// рисуем пустую рамку
.buttonOverlay::after {
    content: '';
    border-radius: 5px;
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    border: 1px solid #EC008C;
}

// при наведении возвращаем кнопку в свою рамку
.buttonOverlay:hover::before {
    transform: translate(6px, -4px);
}

Три эффекта наведения на кнопку.

Нажатая вниз кнопка при наведении (эффект 3)

Этот эффект напоминает сжатую пружину при наведении мыши. Когда мы уводим мышь с кнопки, то пружина отжимается. Весь секрет в обнулении толщины нижней рамки при наведении.


.pressDown {
    background-color: #BA7BA1;
    padding: 10px 30px;
    color: #fff;
    border-radius: 5px;
    border-bottom: 4px solid #EC008C;
    transition: 0.1s;
}

.pressDown:hover{
    border-bottom-width: 0; // обнуление толщины рамки
    margin-top: 3px;
}

Три эффекта наведения на кнопку.

  • Создано 11.05.2020 10:03:11


  • Михаил Русаков

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления

Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

  1. Кнопка:

    Она выглядит вот так: Как создать свой сайт

  2. Текстовая ссылка:

    Она выглядит вот так: Как создать свой сайт

  3. BB-код ссылки для форумов (например, можете поставить её в подписи):

Опыты проводим над кнопкой.


<button>Сюда иди</button>

Создадим базовые правила CSS для кнопки.


button {
    height: 42px;
	border: none;
	background: #3a7999;
	color: #f2f2f2;
	padding: 10px;
	font-size: 18px;
	border-radius: 5px;
	position: relative;
	box-sizing: border-box;
	transition: all 500ms ease; 
}

Мы задали цвет фона и текста, радиусы закругления, размер шрифта, отступы. Для анимации используем transition: all 500ms ease, которое означает, что в нужный момент будут анимированы все свойства в течение 500 миллисекунд.

Горизонтальная заполнение

Полупрозрачный фоновый цвет постепенно заполняет кнопку при наведении. Обычно заполнение происходит с какой-то одной стороны и переход длится до тех пор, пока вся кнопка не будет заполнена.

Чтобы достичь такого результата, нужно использовать псевдо-элемент :before:


button:before {
	content:'';
	position: absolute;
	top: 0;
	left: 0;
	width: 0;
	height: 42px;
	background: rgba(255,255,255,0.3);
	border-radius: 5px;
	transition: all 2s ease;
}

Данный контент абсолютно спозиционирован и расположен в верхнем левом углу кнопки. Зададим ширину равную 0px, потому что именно этот параметр мы будем анимировать. Чтобы анимировать его, мы просто изменим его ширину:


button:hover:before {
	width: 100%;
}

Вертикальное заполнение

Если анимировать высоту, то заполнение произойдёт сверху.


button:before {
	content:'';
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 0;
	background: rgba(255,255,255,0.3);
	border-radius: 5px;
	transition: all 2s ease;
}

button:hover:before {
	height: 42px;
}

Инвертирование цвета

Инвертируем цвет внутри кнопки и добавляем границу:


button:hover {
	background: rgba(0,0,0,0);
	color: #3a7999;
	box-shadow: inset 0 0 0 3px #3a7999;
}

Пунктирная граница

Добавим границу у кнопки и инвертируем цвета:


button {
	border: 3px solid #3a7999;
}

button:hover {
	border: 3px dotted #3a7999;
	color: #3a7999;
	background: rgba(0,0,0,0);
}

Появление значка

При наведении значок плавно появиться слева от текста.

Подключим шрифт со значками Font Awesome.


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

Увеличим внутренний отступ, чтобы для значка было место, и добавим свойство overflow со значением hidden:


button{ 
	padding: 10px 35px;  
	overflow:hidden;
}

Далее добавляем значок из шрифта Font Awesome в псевдо-элемент before и размещаем его за пределами кнопки:


button:before {
	font-family: FontAwesome;
	content:"f07a";
	position: absolute;
	top: 11px;
	left: -30px;
	transition: all 200ms ease;
}

Осталось установить свойство left:


button:hover:before {
	left: 7px;
}

Эффект подпрыгивания

Для данной анимации установим несколько ключевых кадров (keyframes):


@keyframes bounce {
	0%, 20%, 60%, 100% {
		transform: translateY(0);
		transform: translateY(0);
	}

	40% {
		transform: translateY(-20px);
		transform: translateY(-20px);
	}

	80% {
		transform: translateY(-10px);
		transform: translateY(-10px);
	}
}

Подключаем созданную анимацию:


button:hover {
	animation: bounce 1s;
}

Искажение

В CSS3 появилась возможность использовать искажения:


button:hover {
    transform: skew(-10deg);
}

3D-поворот

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

Зададим для свойства transform-style значение preserve-3d, чтобы все дочерние элементы кнопки находились в 3D-пространстве:


button {
	transform-style: preserve-3d;
}

Установим правила для псевдо-элемента after:


button:after {
	top: -100%;
	left: 0;
	width: 100%;
	position: absolute;
	background: #3a9999;
	border-radius: 5px;
	content: 'Flipped';
	transform-origin: left bottom;
	transform: rotateX(90deg);
}

Правила добавлены сверху, перед кнопкой, и выставлены такие же параметры width и border-radius, как и у самой кнопки. Что касается свойств трансформации, то в качестве опорной точки, относительно которой будет происходить трансформация, установлен нижний левый угол элемента и указано вращение по оси X со значением 90 градусов, чтобы элемент казался плоским. Сейчас осталось только создать анимацию при наведении:


button:hover {
	transform-origin: center bottom;
	transform: rotateX(-90deg) translateY(100%);
}

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

Источник

Реклама

Введение в основы современных CSS кнопок

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

Сначала нам нужно освежить в памяти парочку основных моментов по CSS кнопкам. То, что вы понимаете разницу между Flat UI и Material Design, не имеет смысла, если вы не знаете, какие компоненты CSS нужно менять. Быстренько пробежимся по основам CSS кнопок.

Основы CSS кнопок

Для всех сайтов хорошая кнопка это понятие субъективное, но существует парочка общих нетехнических стандартов:

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

Простой текст – Внутри кнопок пишите простой и короткий текст. Пользователи должны сразу понять назначение кнопки и куда она их приведет.

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

Узнать подробнее

Почти все кнопки, которые вы видите в интернете, используют какие-либо смены цветов, рамок и теней. Сделать это можно через различные CSS псевдоклассы. Мы остановимся на двух, :hover и :active. Псевдокласс :hover отвечает за поведение CSS при наведении курсора мыши над объектом. :active по большей части выполняется в момент, когда пользователь нажал кнопку мыши, но еще ее не отпустил.

С помощью псевдоклассов можно полностью изменить внешний вид кнопки, но это не user-friendly подход. Новичкам хорошо добавлять небольшие изменения в основные стили кнопки, почти полностью сохраняя ее внешний вид. В кнопках можно выделить 3 основные момент – цвет, тени и время перехода.

Основной момент 1 – Цвет

Данный параметр меняют чаще всего. Сменить цвет можно с помощью различных свойств, самые простые color, background-color и border. Перед показом примеров давайте разберем, как выбрать цвет кнопки:

Комбинации цветов – Используйте дополняющие друг друга цвета. Colorhexa – замечательный инструмент, там вы сможете найти сочетающиеся цвета. Если вы еще ищите цвета, загляните на Flat UI color picker.

Соблюдайте цвета палитры – Соблюдать цветовую палитру – хорошая практика. Если вы ищите палитры цветов, зайдите на lolcolors.

Основной момент 2 – Тени

С помощью box-shadow объекту можно добавить тень. Каждой стороне можно создать свою собственную тень. Идея реализована как в обоих дизайнах Flat UI и Material Design. Более подробно о свойстве box-shadow можно почитать на MDN box-shadow docs.

Основной момент 3 – Время плавного перехода

Свойство transition-duration добавляет к вашим CSS изменениям временную шкалу. В кнопке без времени плавного перехода стили моментально меняются на стили псевдокласса :hover, что может оттолкнуть пользователя. В этом руководстве много кнопок используют время перехода для того, чтобы кнопки выглядели натуральнее. В примере ниже в состоянии :hover стили кнопки меняются медленно (за 0.5 секунды):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

.colorchange {

  borderradius: 5px;

  fontsize: 20px;

  padding: 14px 80px;

  cursor: pointer;

  color: #fff;

  backgroundcolor: #00A6FF;

  fontsize: 1.5rem;

  fontfamily: ‘Roboto’;

  fontweight: 100;

  border: 1px solid #fff;

  boxshadow: 2px 2px 5px #AFE9FF;

  transitionduration: 0.5s;

  webkittransitionduration: 0.5s;

  moztransitionduration: 0.5s;

}

.colorchange:hover {

  color: #006398;

  border: 1px solid #006398;

  boxshadow: 2px 2px 20px #AFE9FF;

}

А смотрится это так:

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

transitionduration: 0.5s /* Обычная запись, работает во всех современных браузерах */

webkittransitionduration: 0.5s; /* Помогает некоторым версиям safari, chrome и android */

moztransitionduration: 0.5s; /* для firefox */

Есть множество сложных и интересных способов изменять поведение свойства transition, демо выше лишь показали основные моменты.

Три стиля кнопок

1 – Простые черные и белые

Обычно, такие кнопки я добавляю в первую очередь в свои сторонние проекты, так как они просто работают с множеством различных стилей. Данный стиль работает на контрасте черного и белого. Оба варианта одинаковы, поэтому мы рассмотрим код только для черной кнопки с белым фоном. Чтобы перекрасить кнопку в другой цвет, просто поменяйте все white и black местами.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

.suit_and_tie {

  color: white;

  fontsize: 20px;

  fontfamily: helvetica;

  textdecoration: none;

  border: 2px solid white;

  borderradius: 20px;

  transitionduration: .2s;

  webkittransitionduration: .2s;

  moztransitionduration: .2s;

  backgroundcolor: black;

  padding: 4px 30px;

}

.suit_and_tie:hover {

  color: black;

  backgroundcolor: white;

  transitionduration: .2s;

  webkittransitionduration: .2s;

  moztransitionduration: .2s;

}

В стилях выше видно, что свойства font и background-color меняют свои значения со свойством transition-duration: .2s. Это простой пример. Вы можете взять цвета своих любимых брендов и создать свою кнопку. Цвета брендов можно найти на BrandColors.

2- Кнопки Flat UI

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

В демо пять кнопок, но так как у всех меняется только цвет, мы рассмотрим первую.

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

.turquoise {

  marginright: 10px;

  width: 100px;

  background: #1abc9c;

  borderbottom: #16a085 3px solid;

  borderleft: #16a085 1px solid;

  borderright: #16a085 1px solid;

  borderradius: 6px;

  textalign: center;

  color: white;

  padding: 10px;

  float: left;

  fontsize: 12px;

  fontweight: 800;

}

.turquoise:hover {

  opacity: 0.8;

}

.turquoise:active {

  width: 100px;

  background: #18B495;

  borderbottom: #16a085 1px solid;

  borderleft: #16a085 1px solid;

  borderright: #16a085 1px solid;

  borderradius: 6px;

  textalign: center;

  color: white;

  padding: 10px;

  margintop: 3px;

  float: left;

}

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

Узнать подробнее

У кнопки 3 состояния: обычное (без состояния), :hover и :active. Обратите внимание, что состояние :hover содержит всего одну строку с уменьшением прозрачности. Полезный трюк – кнопка становится чуть светлее, и вам не нужно подбирать более светлый цвет.

Переменные в CSS уже не самая новая функция, но некоторые из них тут используются по-другому. Вместо того, чтобы указать сплошную рамку border, тут указываются свойства border-bottom, border-left и border-right, которые создают 3D эффект глубины. Псевдокласс :active часто используется в Flat UI. Когда наша кнопка становится :active происходит 2 вещи:

:border-bottom меняется с 3px до 1px. Тень под кнопкой уменьшается, а кнопка опускается на пару пикселей. Вроде бы просто, но так пользователь чувствует, что он «вдавил» кнопку в страницу.

Изменение цвета. Фон темнеет, имитируя смещение кнопки от пользователя к экрану. И опять, такой простой эффект показывает пользователю, что он нажал кнопку.

Во Flat UI ценятся простые и минималистичные движения кнопок, «рассказывающие большую историю». Многие имитирует сдвиг кнопки с помощью :border-bottom. Стоит также сказать, что во Flat UI есть кнопки, которые вообще не двигаются, а только лишь меняют цвет.

3 — Material Design

Material Design – стиль дизайна, который продвигает идею передачи информации в виде карточек с различной анимацией для привлечения внимания. Material Design создал Google, на странице Material Design Homepage они описали 3 основных принципа:

Слово Материальный не переводится буквально, это метафора

Монотонность, графика, агрессивность

Значение передается при помощи движений

Чтобы лучше понять 3 этих принципа, взгляните на демо MD ниже:

Эти кнопки используют две основные идеи – свойство box-shadow и Polymer. Polymer – фреймворк компонентов и инструментов для создания, упрощающий процесс проектирования веб-сайтов. Если вы работали с Bootstrap, Polymer не сильно отличается. Эффект распространяющейся волны на кнопках выше добавляется всего одной строкой кода.

<div class=«button»>

  <div class=«center» fit>SUBMIT</div>

  <paperripple fit></paperripple> /*вот эта строка добавляет эффект */

</div>

<paper-ripple fit></paper-ripple> — компонент Polymer. Подключив фреймворк в самом начале HTML кода, мы получаем доступ к его компонентам. Подробнее ознакомиться можно на домашней странице Polymer project. Мы разобрались с тем, что такое polymer, и как получить эффект волны (как он работает это тема для другой статьи), теперь поговорим о CSS коде, который с помощью эффекта подпрыгивания исполняет описанные выше принципы.

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

body {

  backgroundcolor: #f9f9f9;

  fontfamily: RobotoDraft, ‘Helvetica Neue’;

}

/* Кнопка */

.button {

  display: inlineblock;

  position: relative;

  width: 120px;

  height: 32px;

  lineheight: 32px;

  borderradius: 2px;

  fontsize: 0.9em;

  backgroundcolor: #fff;

  color: #646464;

  margin: 20px 10px;

  transition: 0.2s;

  transitiondelay: 0.2s;

  boxshadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26);

}

.button:active {

  boxshadow: 0 8px 17px 0 rgba(0, 0, 0, 0.2);

  transitiondelay: 0s;

}

/* Прочее */

.button.grey {

  backgroundcolor: #eee;

}

.button.blue {

  backgroundcolor: #4285f4;

  color: #fff;

}

.button.green {

  backgroundcolor: #0f9d58;

  color: #fff;

}

.center {

  textalign: center;

}

Во всех дизайнах кнопок выше используется свойство box-shadow. Давайте удалим весь неменяющийся CSS код и посмотрим, как box-shadow изменяется и вообще работает:

.button {

  transition: 0.2s;

  transitiondelay: 0.2s;

  boxshadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26);

}

.button:active {

  transitiondelay: 0s;

  boxshadow: 0 8px 17px 0 rgba(0, 0, 0, 0.2);

}

Свойство box-shadow используется для добавления тонкой темной тени слева и снизу у каждой кнопки. По клику тень немного увеличивается и становится светлее – имитируется эффект 3D тени под кнопкой, когда кнопка как бы подпрыгивает от страницы к пользователю. Это движение прописано в стилях Material Design и его принципах. Кнопки в стиле Material Design можно создать с помощью Polymer и box-shadow эффектов.

Слово материальный – метафора – с помощью свойства box-shadow мы имитируем эффект 3D тени, создаем аналог настоящей тени.

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

Значение передается при помощи движений – С помощью Polymer и анимации свойства box-shadow мы можем создавать множество различных движений, когда пользователь кликает на кнопку.

В статье описано, как создавать кнопки по трем разным методологиям. Если вы хотите спроектировать свой собственный дизайн кнопок, рекомендую воспользоваться сервисом CSS3 Button Generator.

В заключение

Черно-белые кнопки довольно просты и понятны. Измените цвета на цвета ваших любимых брендов и вы получите кнопки для вашего сайта. Flat UI кнопки тоже простые: маленькие движения и цвета «рассказывают большую историю». Material Design для привлечения внимания пользователей имитирует крупномасштабные сложные движения, как реальная тень.

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

Редакция: Jack Rometty

Источник: //www.sitepoint.com/

Редакция: Команда webformyself.

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

Узнать подробнее

PSD to HTML

Практика верстки сайта на CSS Grid с нуля

Смотреть

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить цвет кнопки при наведении css
  • Как изменить цвет кнопки после нажатия css
  • Как изменить цвет кнопки winapi
  • Как изменить цвет кнопки contact form 7
  • Как изменить цвет кнопки button

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии