.button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } .button:hover { background-color: #3e8e41; } .button:active { background-color: #4CAF50; box-shadow: 0 5px #666; transform: translateY(4px); }
以上是一个典型的按钮样式,在这个样式中,大家使用了:hover、:active伪类来实现点击事件。当鼠标滑过按钮时,按钮的颜色会变得更加深色;当按钮被点击时,按钮会有一个阴影,并且会向下平移一些距离。
除了伪类,CSS还提供了一些伪元素,它们用于为元素添加不同的效果,如:before、:after等。下面是一个示例:
.container { width: 200px; height: 200px; position: relative; } .container:before { content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; background-color: rgba(255,255,255,0); transition: background-color 0.3s; } .container:hover:before { opacity: 1; background-color: rgba(255,255,255,0.5); }
在这个样式中,大家使用了:before伪元素来添加一个半透明的背景,当鼠标滑过容器时,背景会变得更加明亮。这里使用了transition属性来制作渐变效果。
总之,CSS拥有丰富的选择器、伪类、伪元素等特性,通过它们,大家可以实现各种交互效果,让网页更加丰富多彩。