如何为伪元素制作悬停效果?
我有一个这样的设置:
<div id="button">Button</div>
对于CSS:
#button {
color: #fff;
display: block;
height: 25px;
margin: 0 10px;
padding: 10px;
text-indent: 20px;
width: 12%;
}
#button:before {
background-color: blue;
content: "";
display: block;
height: 25px;
width: 25px;
}
有没有办法给伪元素一个悬停效果,例如 #button:before:hover {...}
并且是否也可以得到悬停的伪元素以响应另一个悬停的元素,如下所示:#button:hover #button:before {...}?仅 CSS 就可以了,而且 jQuery 也可以。
I have a this setup:
<div id="button">Button</div>
and this for CSS:
#button {
color: #fff;
display: block;
height: 25px;
margin: 0 10px;
padding: 10px;
text-indent: 20px;
width: 12%;
}
#button:before {
background-color: blue;
content: "";
display: block;
height: 25px;
width: 25px;
}
Is there a way to give the pseudo element a hover effect such as #button:before:hover {...}
and is it also possible to get the pseudo element to hover in response to another element being hovered like so: #button:hover #button:before {...}
? CSS only would be nice, but also jQuery is fine too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以根据父元素的悬停来更改伪元素:
JSFiddle DEMO
You can change the pseudo-element based on hover of the parent:
JSFiddle DEMO
澄清一下,您不能将
:hover
赋予伪元素。截至 2018 年,CSS 中还没有::after:hover
这样的东西。To clarify, you CAN NOT give
:hover
to a pseudo element. There's no such thing as::after:hover
in CSS as of 2018.#button:hover:before
将更改伪元素以响应按钮悬停。但是,如果您只想对伪元素执行任何重要操作,那么最好将实际元素放入 HTML 中。伪元素相当有限。虽然 CSS 不允许您根据后面的元素设置元素样式,但通常可以通过将 :hover 放在父节点上来装备具有相同基本效果的东西,即:
#button:hover:before
will change the pseudo-element in response to the button being hovered. If you want to do anything nontrivial to the pseudo-element only, however, you'd be better off putting an actual element into your HTML. Pseudo-elements are rather limited.While CSS won't let you style elements based on elements that come after them, it is usually possible to rig something with the same basic effect by putting :hover on a parent node, i.e.:
如果只是出于设计目的,我认为最好在矩形框的两侧创建伪元素并保持 HTML 尽可能简单:
HTML:
CSS:
我修改了 CSS,结果如下所示:
http://jsfiddle.net/a3ehz5vu/
If its just for design purposes I think its better to create Pseudo-Elements on either side of the Rectangle Box and to keep the HTML as simple as possible:
HTML:
CSS:
I've modified the CSS and the result can be seen below:
http://jsfiddle.net/a3ehz5vu/