使用 :hover 时避免将样式应用于 :after
Avoid applying style to :after when using :hover
我正在使用 :after 来为自己设置一个带有半径和渐变的边框,例如:
#main .element {
border-radius: 10px;
background: #FFF;
}
#main .element:after {
border-radius: 10px;
background: linear-gradient(red, blue);
top: -7px;
bottom: -7px;
left: -7px;
right: -7px;
z-index:-1;
}
我希望相关元素在悬停时更改其背景颜色,例如:
#main .element:hover {
background: #F00;
}
问题是 :after 伪元素也被选中,并且它的背景也发生了变化 - 我不希望 :after 样式在悬停在元素上时受到影响 - 我希望边框保持其背景颜色。
关于如何执行此操作的任何建议?我更愿意使用 CSS 但我不反对在需要时使用 jquery 。谢谢
问题不在于 :after
是从父级继承样式,如 this jsfiddle shows。
您的问题是 :after
的 css 缺少几个关键属性:
#main .element:after {
/* :before and :after elements *must* have `content` set, even if it is empty*/
content: "";
border-radius: 10px;
background: linear-gradient(red, blue);
/* :after also doesn't have any size, since you never position it. Without a non-static position, top, bottom, etc. are ignored*/
position:absolute;
top: -7px;
bottom: -7px;
left: -7px;
right: -7px;
z-index: -1;
}
我正在使用 :after 来为自己设置一个带有半径和渐变的边框,例如:
#main .element {
border-radius: 10px;
background: #FFF;
}
#main .element:after {
border-radius: 10px;
background: linear-gradient(red, blue);
top: -7px;
bottom: -7px;
left: -7px;
right: -7px;
z-index:-1;
}
我希望相关元素在悬停时更改其背景颜色,例如:
#main .element:hover {
background: #F00;
}
问题是 :after 伪元素也被选中,并且它的背景也发生了变化 - 我不希望 :after 样式在悬停在元素上时受到影响 - 我希望边框保持其背景颜色。 关于如何执行此操作的任何建议?我更愿意使用 CSS 但我不反对在需要时使用 jquery 。谢谢
问题不在于 :after
是从父级继承样式,如 this jsfiddle shows。
您的问题是 :after
的 css 缺少几个关键属性:
#main .element:after {
/* :before and :after elements *must* have `content` set, even if it is empty*/
content: "";
border-radius: 10px;
background: linear-gradient(red, blue);
/* :after also doesn't have any size, since you never position it. Without a non-static position, top, bottom, etc. are ignored*/
position:absolute;
top: -7px;
bottom: -7px;
left: -7px;
right: -7px;
z-index: -1;
}