I'd like to create a button
that changes its style when it gets pressed. This is my CSS code:
button { font-size: 18px; border: 2px solid gray; border-radius: 100px; width: 100px; height: 100px; } button:active { font-size: 18px; border: 2px solid red; border-radius: 100px; width: 100px; height: 100px; }
<button>Button</button>
It is changed only when I click & hold on it. I want to make it change style after it's pressed. For example, normal state would be white, state while being clicked would be green and after click is released it would be red.
Unfortunately, there is no :click pseudo selector. If you want to change styling on click, you should use Jquery/Javascript. It certainly is better than the "hack" for pure HTML / CSS.
Method 1: We can use CSS transform property to add a pressed effect on the button when it is active. CSS transform property allows us to scale, rotate, move and skew an element.
The “+” selector in the CSS code is telling the browser to select the label element directly placed after the input element.
You can do this if you use an <a>
tag instead of a button. I know it's not exactly what you asked for, but it might give you some other options if you cannot find a solution to this:
Borrowing from a demo from another answer here I produced this:
a { display: block; font-size: 18px; border: 2px solid gray; border-radius: 100px; width: 100px; height: 100px; text-align: center; line-height: 100px; } a:active { font-size: 18px; border: 2px solid green; border-radius: 100px; width: 100px; height: 100px; } a:target { font-size: 18px; border: 2px solid red; border-radius: 100px; width: 100px; height: 100px; }
<a id="btn" href="#btn">Demo</a>
Notice the use of :target
; this will be the style applied when the element is targeted via the hash. Which also means your HTML will need to be this: <a id="btn" href="#btn">Demo</a>
a link targeting itself. and the demo http://jsfiddle.net/rlemon/Awdq5/4/
Thanks to @BenjaminGruenbaum here is a better demo: http://jsfiddle.net/agzVt/
Also, as a footnote: this should really be done with JavaScript and applying / removing CSS classes from the element. It would be much less convoluted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With