Home > Article > Web Front-end > How to change color on click in css
Method: 1. Use the “:active” pseudo-class and cooperate with the “:focus” pseudo-class. You only need to set the “:active” pseudo-class and the “:focus” pseudo-class to the same background color to achieve the effect. ; 2. Use the tabindex attribute to control the order, and use the ":focus" pseudo-class to achieve color change after clicking without disappearing.
The operating environment of this tutorial: Windows 7 system, CSS3&&HTML5 version, Dell G3 computer.
You can achieve the color-changing effect of clicked elements by using css pseudo-classes. The two pseudo-classes are: active, :focus
1, :active: used to select active links. When a link is clicked, it becomes active (activated). The :active selector applies to all elements, not just link a elements
:focus: Used to select the element that has received focus. The :focus selector is only allowed on elements that receive keyboard events or other user input.
Due to the above characteristics, if you want to achieve the effect of changing color when clicked, there are two methods. The difference between the two is
: active. The element changes color when clicked, but the color disappears after clicking.
: focus, the element changes color after being clicked, and the color does not disappear after being clicked
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>document</title> <style> button:active{ background:olive; } button:focus{ background:olive; } </style> </head> <body bgcolor="#ccc"> <button>cmcc</button> </body> </html>
Effect:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>document</title> <style> div{ background: #fff; border:1px solid rgb(59, 59, 59); border-radius: 5px; margin: 10px 0; } div:focus { background-color:red; } </style> </head> <body bgcolor="#ccc"> <div tabindex="1"> Section 1 </div> <div tabindex="2"> Section 2 </div> <div tabindex="3"> Section 3 </div> </body> </html>Effect:
Recommended learning:
The above is the detailed content of How to change color on click in css. For more information, please follow other related articles on the PHP Chinese website!