Css btn click effect

How to make a button click effect in CSS

Here you’ll learn how to make the button press-in effect in CSS. We’ll tell you ahead of time that there’s nothing complicated here, any beginner will be able to cope with it.

Example

What we end up with (click the button):

What do we need to know? You must know what a pseudo-element is (:before and :after) and what pseudo-classes are (:hover, :active). You should understand how to add a shadow to an element and how you can move the element with the transform property.

Writing the code

Let’s create our button in HTML:

Now, let’s move on to configuring the CSS. First, let’s rewrite the properties of button, which are set by default:

Now you can move on to the visual appearance of the button. Let’s set the text color, background, border, padding, and other little things.

So, we should get our button like this:

So far, nothing special. But let’s move on to pseudo-elements. Let’s add :before

And now we have a button with a 3D effect. We set the pseudo-element with background and shadow, which allowed us to achieve this effect. We also lowered it just below the main frame of the button. This is what we got:

Now let’s make a press-in effect when hovering over the button. It will be pressed in slightly, not entirely.

To do this, we lower the main frame below by changing its background a bit and slightly reducing the shadow (box-shadow) for the pseudo-element:

button.btn:hover < background: #ffe9e9; transform: translate(0, 0.25em); >button.btn:hover::before

A button like this comes out (hover over it!):

And the final touch, let’s change the styles in condition :active

button.btn:active < background: #ffe9e9; transform: translate(0em, 0.75em); >button.btn:active::before

When the button is active (the user has clicked it), we move the main part of the button slightly and remove the shadow.

That’s it, the button press-in effect is ready!

Final code

Video

Источник

Pure CSS Click Effect With Animation | HTML CSS Button Press Effect

pure css click effect

Previously I have shared button hover effects , but this is a click effect that you can use on any element not only button. Basically, when we click on an element or button on modern websites and apps, there is an animation effect on click. We can create a kind of button press effect using pure HTML and CSS.

Today you will learn to create HTML CSS Button Press Effect. This is related to a little bit ripple effect , but its animation spread on outside the button. Basically, there are 4 icons and all the icons have the same click effect. When you will click on any icon then there will an effect reveal on the backside of the icon like a multi-circle spreading.

So, Today I am sharing Pure CSS Click Effect With Animation. There I have used pure CSS to create the effect because, the animation is very basic which we can create using basic CSS command. I did not use JS or any other library to creating this, and I have shared many buttons related program in the past you can check out.

If you are thinking now how this click animation actually is, then see the preview given below.

Preview Of HTML CSS Button Press Effect

See this video preview to getting an idea of how this button press effect looks like.

Now you can see this visually, also you can see it live by pressing the button above. If you like this, then get the source code of its.

Pure CSS Click Effect With Animation Source Code

Before sharing source code, let’s talk about it. First I have created a main div named container and placed 4 divs inside it. In all four divs I have placed a same class name “button” and inside each button div, I have placed a span tag. The span tag is for placing the icon, all these icons are based on ionicons (get).

Now using CSS I have placed all the elements in the right place, as you can see in the preview. I have placed items in the center using position & text-align command. After that, I gave the height and width to the icons and created a blank content with white background for creating the background circle. And finally for creating the animation I have used CSS @keyframe command and scale up the circle in 3 parts.

Left all other things you will understand after getting the codes, I can’t explain all in writing. For creating this effect program, you have to create only 2 files. First file for HTML and second for CSS. Follow the steps to creating this without any error.

Create an HTML file named ‘index.html‘ and put these codes given below.

Источник

Как сделать эффект нажатия при клике на кнопку, используя CSS и JavaScript

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

Автор статьи - Олег Толочко

  • при загрузке страницы добавляем обработчик событий на кнопку
  • при клике добавляем кнопке определенный класс, который удаляем через N времени
  • у этого класса задаем CSS анимацию с необходимыми эффектами

Давайте разберем на конкретном примере.

Сначала создайте простой каркас страницы с кнопкой:

Теперь зададим базовые стили для страницы и кнопки (они необязательны, это для красоты примера).

/* Убираем отстыпы по умолчанию */ body, html { margin: 0; padding: 0; } .main { /* Задаем высоту и стили общего блока */ height: 400px; background-color: #f5f5f5; /* Выравниваем кнопку по центру */ display: flex; justify-content: center; align-items: center; } .button { background-color: #000; color: #fff; padding: .75em 1.5em; cursor: pointer; transition: box-shadow 200ms linear; } .button:hover { box-shadow: 0 .5em 1em 0 rgba(0, 0, 0, 0.15), 0 .4em .5em -.4em rgba(0, 0, 0, 0.4); }

А вот обязательный CSS — сам эффект при нажатии.

.button { position: relative; } .button:after { content: ''; position: absolute; top: 50%; left: 50%; margin: -40px 0 0 -40px; width: 80px; height: 80px; border-radius: 50%; opacity: 0; box-shadow: inset 0 0 0 35px rgba(0,0,0,0.1); display: none; } .button.click:after { animation: animate-click 0.6s ease-out forwards; display: block; } @keyframes animate-click { 0% { opacity: 1; transform: scale3d(0.4, 0.4, 1); } 80% { box-shadow: inset 0 0 0 2px rgba(0,0,0,0.1); opacity: 0.1; } 100% { opacity: 0; box-shadow: inset 0 0 0 2px rgba(0,0,0,0.1); transform: scale3d(1.2, 1.2, 1); } }

Разберем как это работает. Сначала добавляем после кнопки блок эффекта, задаем ему размеры и позиционирование. По умолчанию блок скрыт. У него есть внутренняя тень, которая заполняет почти весь блок.

Далее прописываем анимацию, если у кнопки добавлен класс .click. Обычно анимацию добавляют, например, при наведении на элемент, но в нашем примере класс будет добавляться блоку скриптом. И анимация будет срабатывать каждый раз, когда у кнопки появляется этот .click. Без скрипта такая анимация сработает просто при загрузке страницы.

Прописываем саму анимацию. Сначала блок уменьшается в размерах до 40% свойством transform: scale3d(0.4, 0.4, 1); . Потом следует плавное снижение прозрачности и уменьшение внутренней тени, то есть она стягивается от центра к краям, что визуально выглядит, как увеличение блока. При этом сам блок увеличивается, становясь прозрачным, это добавляет эффект волнообразного исчезания тени, как будто она догоняет расширяющийся блок.

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

// После загрузки документа document.addEventListener("DOMContentLoaded", () => { // Определяем блок кнопки const button = document.querySelector('.button'); // Вешаем прослушиватель события по клику на кнопку button.addEventListener("click", (event) => { // Определяем элемент по которому кликнули const elem = event.target; elem.classList.add('click'); // Добавляем блоку класс .click setTimeout(function() { elem.classList.remove('click'); // Удаляем класс .click через 400ms }, 400); }); });

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

Источник

Читайте также:  Android java audio source
Оцените статью