CSS transition-delay与transition-duration属性不生效问题求助
问题原因与修复方案
- 代码结构错误:你当前将CSS样式写在了
<script>标签内,浏览器会将这段内容识别为JavaScript代码执行,样式规则完全不会生效,CSS需要写在<style>标签内,或者你代码中引入的外部style.css文件中。 - 过渡属性值不支持动态计算:CSS transition 正常生效的前提是过渡的属性在初始状态、触发状态(本次为hover状态)都为可计算的固定数值类型。你在hover状态将
width设置为auto,浏览器无法计算10px到auto的中间过渡值,因此过渡动画不会触发。
修复后的完整代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>::AFTER & :: BEFORE</title> <style> body { height: 100vh; display: flex; justify-content: center; align-items: center; font-size: 5rem; } p::before { content: ""; background-color: red; display: block; width: 10px; height: 10px; transition: all ease-in-out 250ms; } p::after { content: ""; background-color: red; display: block; width: 10px; height: 10px; transition-property: width; transition-delay: 1s; transition-duration: 2s; } p:hover::before, p:hover::after { /* 替换auto为可计算的数值,这里设置为和父元素p同宽 */ width: 100%; } </style> </head> <body> <p>Here is some content</p> </body> </html>
可选优化方案
如果需要过渡到和伪元素内容匹配的自适应宽度,不需要固定值,可以把过渡属性换成max-width:初始状态设置max-width: 10px,hover状态设置max-width: 1000px(设置一个远大于你预期最大宽度的数值即可),也能实现类似的过渡效果,避免auto无法过渡的问题。
内容的提问来源于stack exchange,提问作者Rukuii
相关产品推荐
相关产品推荐

