我知道 !important
不推荐使用,少数已知的合适用例包括使用第三方库(例如 Bootstrap)时。但是,我想问一下这个用例是否也合适。假设我有一个 <div/>
我想从背景颜色透明到某种颜色设置动画。但是,我也想在动画发生后在悬停时改变颜色,但我似乎无法找到不使用 !important
的方法来做到这一点。规则。提前致谢!
div{
position: absolute;
width: 100px;
height: 100px;
animation: animate 4s forwards;
}
div:hover{
background-color: blue !important;
}
@keyframes animate{
from {
background-color: transparent;
}
to {
background-color: maroon;
}
}
最佳答案
这里不判断是否适合使用 !important
,在您的情况下,一种解决方法是将动画和过渡拆分为两个不同的元素。请注意,当您想要对相同的属性进行动画处理和过渡时,这样做是很常见的。
background-color
甚至具有可以使用伪元素代替普通元素的优势。
少说话,多代码:
div{
position: absolute;
width: 100px;
height: 100px;
animation: animate 4s forwards;
}
div::after {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
transition: background-color 2s;
}
div:hover::after{
background-color: blue;
}
@keyframes animate{
from {
background-color: transparent;
}
to {
background-color: maroon;
}
}
<div></div>
关于html - 这是 CSS !important 规则的正确用例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65462735/