如何使用CSS或JavaScript实现div hover时周围显示多色边框效果
多色hover边框实现方案
下面提供两种常用的多色边框修改方案,可按需选择:
方案1:渐变彩色边框(支持流动动画)
利用渐变背景实现多色边框效果,可额外添加动画实现颜色流动效果,修改后的CSS代码如下:
.container{ display: flex; justify-content: center; align-items: center; flex-direction: row; } .container a{ position: relative; width: 200px; height: 60px; display: inline-flex; justify-content: center; align-items: center; z-index: 0; margin: 20px; color: #333; text-decoration: none; } .container a::before, .container a::after { content: ''; position: absolute; inset: 0; transition: 0.5s; } /* 渐变外边框层 */ .container a::before{ /* 可自定义渐变角度、颜色数量和色值 */ background: linear-gradient(45deg, #ff3b30, #ff9500, #ffcc00, #34c759, #007aff, #5856d6, #af52de); /* 开启流动动画时需要加下面两行 */ background-size: 400%; animation: gradientRun 3s linear infinite; } /* 内部白色遮盖层 */ .container a::after{ background: #fff; } .container a:hover::before { inset: -3px; } /* 文字层级高于伪元素,避免被遮挡 */ .container a > * { position: relative; z-index: 1; } /* 渐变流动动画,不需要可以删除 */ @keyframes gradientRun { 0% { background-position: 0 0; } 100% { background-position: 400% 0; } }
方案2:四侧边分别固定不同纯色
如果需要四个边分别对应独立的纯色,可使用四个伪元素分别控制四个边的颜色和动画,修改后的代码如下:
.container{ display: flex; justify-content: center; align-items: center; flex-direction: row; } .container a{ position: relative; width: 200px; height: 60px; display: inline-flex; justify-content: center; align-items: center; margin: 20px; color: #333; text-decoration: none; } /* 四个伪元素分别对应上、右、下、左四个边 */ .container a::before, .container a::after, .container a .text::before, .container a .text::after { content: ''; position: absolute; transition: 0.5s; } /* 上边:红色 */ .container a::before{ width: 0; height: 3px; top: 0; left: 0; background: #ff3b30; } /* 右边:蓝色 */ .container a::after{ width: 3px; height: 0; top: 0; right: 0; background: #007aff; } /* 下边:绿色 */ .container a .text::before{ width: 0; height: 3px; bottom: 0; right: 0; background: #34c759; } /* 左边:黄色 */ .container a .text::after{ width: 3px; height: 0; bottom: 0; left: 0; background: #ffcc00; } /* hover时四个边展开 */ .container a:hover::before, .container a:hover .text::before{ width: 100%; } .container a:hover::after, .container a:hover .text::after{ height: 100%; } /* 文字层级提升,避免被遮挡 */ .container a .text { position: relative; z-index: 1; }
使用该方案需要调整HTML结构,在a标签内用class为text的标签包裹文字内容,示例如下:
<div class="container"> <a href="#"> <span class="text">按钮内容</span> </a> </div>
内容的提问来源于stack exchange,提问作者Aab B
相关产品推荐
相关产品推荐

