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

Как из div сделать кнопку

  • автор:

How to Style Buttons with CSS

Styled buttons help you create cool websites. There are a lot of styles that you can apply to the buttons. Here is the guide to styling buttons.

1. Create a button

At first, create a <button> element.

2. Style your button

So, it is time to apply styles to your button. Let’s do it step by step.

We’re starting by adding these styles:

  • display: inline-block to enable the ability to add width and height to our button
  • background-color: #7b38d8 a fancy background color for the button
  • padding: 20px makes a bit more room for our button in all four sides
  • width: 200px gives a 200px width
  • color: #ffffff makes our Submit text white
  • text-align: center; puts our text in the center

Let’s see what we’ve got so far:

Now, we’re going to round our borders and use the border property. Also, let’s make our text a bit larger. So add these lines to the code:

Here’s the result

Much better, right?

Let’s add cursor: pointer to have the handicon while bringing our cursor to the button and give it a bit margin of 5px, so :

Here’s the updated result, try to move your cursor towards the button!

You need to be aware of a tiny difference here. In the previous example, when we move the cursor to the Submit text, it’ll be turned to a hand. But now the whole button will turn to a hand as soon as we move the mouse towards it!

3. Style the hover state

Your third step is to style the hover state to give visual feedback to the user when the button’s state changes.

Here’s the result, but we have a problem!

Changing the colour on hover is too fast, and it’s not so pleasant!

So let’s add transition and be careful that we have to use it in the button element, not in its hover state.

I like it! So much better!

Now, as the last step, let’s add functionality to our beautiful button. We want to open an alert whenever clicking on this button.

So click on the button below, and let’s greet!

We just used onclick event of javascript and alert something on the screen after clicking the button!

Now let’s see an interesting example using the <button> element.

Example of styling a button created with the <button> tag:

The codes you see here are similar to what we’ve done in the previous example.

Here, we used a span tag inside of the button. We can later use the :after pseudo-class to create a creative hover effect.

We’ll place the arrow sign » on our button, which will show it on the hover effect of the mouse, with a smooth transition.

Here’s the essential part of the above code:

Here’s the result:

Example of styling a button created with the <span> tag:

The code above is the final code, and you can see the result in the «Try it Yourself» section.

Now let’s break down the code and explain the tricky parts to make you understand it well. We explain that parts in snippets below as comments in front of each line.

We applied some general styles on body, and then we have a wrapper class which acts like a wrapper parent for two tags which in this example will be treated like buttons.

You can read the comments below for more explanation.

Example of styling a button created with the <a> tag:

Let’s learn what happens here in the essential parts of the code.

Example of styling the <button> element:

Let’s break down the tricky parts of the code!

But before that, please note that these examples just give you a hint or a whole idea of being creative with buttons to build or use on your web journey!

The best way to understand them is to open it in the demo section (Try it Yourself!) and play with the properties or have it in your code editor and check them.

We give you the hints and necessary tips and explanations that you may need along the way to understand it better.

So with that being said, let’s explain some essential parts of the above code:

Example of styling some <button> elements:

And here’s another example, let’s explain some tricky parts of it down below:

How to style a div like the button-element?

I’ve noticed that when using the <button></button> element, the browsers will naturally assume that you want to center the inline content, and that the element is clickable. Is it possible to have a div behave in the same way through css? I went through the UA-stylesheet to see if I could figure it out, but nothing made it center it vertically.

The only other way i know to get the same result is with 2 divs. One wrapper with display: table , and a div with display: table-cell and vertical-align: middle .

But that creates an extra div. Is it possible to achieve the same behaviour with just one element?

Converting divs into accessible pseudo-buttons

Let’s get this out of the way right now: I don’t think there is a compelling reason to turn an unopinionated HTML element like a div or a span into a button. ’Cause, you know, button already exists.

However, the question was asked, “If you had to do it though, could it be done?”.

This post attempts to take you through the steps of how to, in some ways, convert an unopionated HTML element into a accessible ‘pseudo-button’, and hopefully convinces you to just use a button .

I’ve ruminated on the use of button element before. That was four years ago. My opinion today differs. I don’t care about the speed impact; a button is slower because it does more. What’s more, for the number of buttons you are going to have on almost any page/app it adds up to very little overhead in real terms. I don’t think this is a sensible place to make economies.

The button element gives you things you might not see or appreciate but others might.

button powers

What does a button give you that other elements don’t? Here are a few choice features:

A button can receive focus. For the uninitiated this means someone can move to that element easily with, for example, just a keyboard. It gets a tabIndex whether or not you set it.
It supports an accessKey so you can set a keyboard shortcut to simply activate it.
It supports the disabled attribute, which, when added means the button stops receiving clicks.
It has a type attribute, allowing it to submit the form it lives in, if the type is set to submit . It can also reset a form type="reset" or just do nothing type="button" .
It has a value property, so you can conveniently set a different value than the text should you need it for scripting.

There are a bunch more features. If you’re interested, here are the details of the button element in the HTML 5.2 specification.

Meanwhile, an unopionated element, like a div gives you nothing. Hence the reason it’s demonstrably faster to render than a button.

Making a div more accessible

Hopefully that covers why you wouldn’t want to do this?

Well, as promised at the outset, we are going to see how far we can get anyway!

Say hello to our div :

role=“button”

ARIA (Accessible Rich Internet Applications) attributes provide the means to make a div appear as a button to a screen reader. Here is the intro to the button role page on MDN:

Adding role=“button” will make an element appear as a button control to a screen reader. This role can be used in combination with the aria-pressed attribute to create toggle buttons.

Right, so now our button would look like this:

aria-pressed

In our instance the button is going to be a switch; it can be pressed or not. With ARIA we could also make it the control for something like a menu with aria-expanded but instead we will use aria-pressed . So default it will need that too:

tabindex

We need the buttons to be focusable. That means we need a tabindex. By default we want the button to follow the normal sequence so we can set it to “0”. If you are unfamiliar with tabindex you should know that a negative number means the element is focusable but not in the normal focus sequence/sequential keyboard navigation. You want this if you have a modal that you want focusable but only via script, where you would use focus() when appropriate.
A tabindex of “0” means the element is focusable and happy to follow the normal order. A positive value e.g “1” provides an indication to the browser of how that element should be prioritised in the focus order. If you had elements with tabindex 1,2,3 respectively, your intention would be for the browser to focus them in ascending order. First 1, then 2, then 3. Note, it’s just an indication, not a promise! You should also avoid doing that unless you absolutely know you need to though; it’s liable to create an unpredictable experience for keyboard users. Just go with The Web’s Grain.

Right, with the tabindex attribute in, we are now looking like this:

keyboard event handlers

If you have a button element that has focus, pressing space, or enter will activate the button. When you convert a different element with role="button" you don’t get that functionality for free. You need to add your own keyDown listeners. You can add the listener to individual elements or, thanks to event bubbling, you can listen on a containing element. For example:

disabled (updated – thanks Darek)

The button element has a disabled state built in. When this is present, keyboard actions on the button are ineffective. For a pseudo-button you would need to add this functionality. Stylistically, this could be achieved easily enough. Something like:

However, you would still need to add the correct aria-* attribute, so that assistive technology knows what to do with the element. Without aria-disabled applied to the element it would only be visually ‘disabled’; not functionally.

Styles

There is no way point dancing around this – the button element is not straightforward to style. Browsers have opinions on how a button should look and you need to consider that.

However, switching out a button for a pseudo-button isn’t going to negate that need. Once an element has role="button" it is focusable and as a consequence, browsers indicate this focus in the same manner they would a real button . You will need to consider focus states and styles for when a button is toggled. If you are switching off the default outline for example, make sure you are adding a suitable sustitute.

Example pseudo-buttons

The MDN role="button" documentation gives solid examples that I have amended for this example. Here are a number of divs in a wrapping div. Pressing “Convert to pseudo-buttons” decorates the divs with the necassary attributes and event listeners to give us some of buttons goodnes. You can tab across them and pressing space or enter when one is selected toggles the aria-pressed attribute to indicate the state of the button.

Or you can view the embed here:

Summary

Makming unopionated elements into pseudo-buttons is not a trivial task. A lot of work has to be done, and therefore going forward, managed, to give pseudo-elements just some of the functionality built into the native button element.

There are inherent challenges and arguably shortcomings in dealing with buttons in some situations but appreciate that the friction is likely due to the fact that you are going against the grain of the medium you are working with.

Despite any frustrations, I’d suggest the end result will be far smoother if you choose to work with the grain instead.

If you enjoyed this post and/or it was useful, Say thanks with a coffee. ��

The 4th Edition of the best—selling ‘Responsive Web Design with HTML5 and CSS’.

9 comments:

Hi Ben, Looks like nothing is happening when I press all those buttons! Something wrong?

Hi, are you pressing the ‘convert to pseudo-buttons’ button at the bottom first? Once that is done you should be able to press tab inside the wrapper and space to toggle selection of the focused button?

I did, but nothing more.

Hi, thanks for this article
Can you write examples or proof when button real slowly then div.
I think it’s very rare case or not?

Hi Dmitry, tests and explainer already linked at the beginning of the article: https://benfrain.com/we-need-a-better-button-its-too-slow-and-wont-behave/

TL;DR extremely rare!

Hi, your “disabled” section is incomplete. While you have adjusted the styling and prevented click events, the button is still almost fully usable. This means I can focus the button and I can activate the button with Enter/Space.
Additionally, you have to use “aria-disabled” as per WAI-ARIA Authoring Practices. For a button, “disabled” is converted into “aria-disabled”, while this does _not_ work for “disabled” or “data-disabled” within a div.

This is my go-to example on why you really would never want to re-implement a button (which you are also emphasizing in your article).

Hi Darek, I’ll add a little more about disabled in the main copy as you are quite right; it’s an essential factor in making something a button and needs factoring in. No idea why I used data-disabled in the original example! Thanks for the catch.

Thanks for this article. I am curious what your thoughts are on setting up a label element as a “pseudo-button” in order to enable progressive enhancement for CSS-only dialogs, carousels and so on?

The most frustrating thing about this topic, for me, is that right now it seems to me that there is an inevitable trade-off between accessibility and requiring javascript.

There *are* CSS-only methods for a lot of design patterns that traditionally rely on JS, but these are not accessible. These are mostly done with the “checkbox hack”, hence the use of labels.

I am very tempted to try setting up a label system with the pseudo-button functionality you described. I am curious about what your, or other people’s thoughts might be. It seems to be the strongest use-case for a pseudo-button.

Как сделать кнопку в html из любого элемента на сайте

Многим известно, что для создания простой кнопки на html достаточно использовать тэг button или воспользоваться формой. Но как сделать кнопку абсолютно из любого элемента на сайте. Один из способов представлен в данной статье.

Он заключается в использовании события на jаvascript — onclick. Допустим, у нас имеется блок div с текстом

Дописываем к этому блоку событие onclick, в нем указываем команду для отображения сплывающего сообщения.

<div onclick=”alert(‘Кнопка нажата’)”>Текст</div>

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

<div onclick=”alert(‘Кнопка нажата’)” style=”cursor:pointer;”>Текст</div>

Параметр cursor отвечает за изменение курсора мыши при наведении на объект.

<div onclick=»alert(‘Кнопка нажата’)» style=»cursor:pointer;border-width:1px;border-style:solid;background-color:gray;width:100px;text-align:center;color:#ffffff;»>Текст</div>

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

Как было указано ранее, кнопку таким способом можно сделать из любого элемента на html странице.

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

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