概览
此篇文章主要介绍文字悬浮下划线的动画效果,主要有从左往右和从中间至两边扩散两种动态效果
一. 从左往右
示例代码如下
<!DOCTYPE html>
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>xiahuaxian</title><style>.title {color: #333;line-height: 2;/* position: relative; */display: inline-block;}.title span {background: linear-gradient(to left, red, blue) no-repeat right bottom;background-size: 0% 2px;transition: background-size 1s ease;}.title:hover span {background: linear-gradient(to right, red, blue) no-repeat left bottom;background-size: 100% 2px;}</style>
</head><body><h2 class="title"><span>文字移入一段文字中下划线从左往右变长,然后鼠标移出又从左往右退出的效果,文字移入一段文字中下划线从左往右变长,然后鼠标移出又从左往右退出的效果,文字移入一段文字中下划线从左往右变长,然后鼠标移出又从左往右退出的效果,文字移入一段文字中下划线从左往右变长,然后鼠标移出又从左往右退出的效果。</span></h2></body></html>
优点:支持多行悬浮的动画效果
二. 从中间扩展
示例代码如下:
<!DOCTYPE html>
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>xiahuaxian</title><style>.title {color: #333;line-height: 1.5;display: inline-block;}.title span {position: relative;display: inline-block;}.title span::after {content: '';position: absolute;bottom: 0;left: 50%;/* Center the animation horizontally */width: 0%;/* Start with no width */height: 2px;background: linear-gradient(to right, red, blue);/* Gradient from right to left */transition: width 1s ease, background 1s ease, left 1s ease;/* Smooth transition for width, background, and left position */}.title:hover span::after {width: 100%;/* Expand to full width */background: linear-gradient(to left, red, blue);/* Change gradient direction */left: 0;/* Move the gradient to the left */}</style>
</head><body><h2 class="title"><span>文字移入一段文字中</span></h2></body></html>
缺点: 对于多行文字,只有最后一行有下划线
三. 知识点梳理
1. transition
CSS的transition属性用于在一定的时间区间内平滑地改变一个元素从一个样式到另一个样式。它允许元素从一种样式逐渐改变为另一种样式,而不是立即改变。这对于创建动态和吸引人的用户界面非常有用。
transition属性是一个简写属性,用于在一个给定的持续时间内应用动画效果。它包含以下四个子属性:
(1)transition-property: 指定应用动画的CSS属性名称。你可以指定一个属性名称,如width、height、background-color等,或者使用all来指定所有可动画的属性。
(2) transition-duration: 定义动画完成一个周期所需的时间。它通常以秒(s)或毫秒(ms)为单位。例如,2s表示动画将在2秒内完成。
(3) transition-timing-function: 定义动画的速度曲线。它可以有以下值之一:linear(匀速)、ease(慢到快再到慢)、ease-in(慢到快)、ease-out(快到慢)、ease-in-out(慢到快再到慢)或cubic-bezier()(自定义速度曲线)。
(4)transition-delay: 定义动画开始前的延迟时间。它通常以秒(s)或毫秒(ms)为单位。例如,1s表示动画将在1秒后开始。
2. linear-gradient
linear-gradient 是 CSS 中的一个属性,用于创建线性渐变背景。线性渐变是一种颜色之间的平稳过渡,从一种颜色线性地过渡到另一种颜色。
linear-gradient 的基本语法如下:
linear-gradient(direction, color-stop1, color-stop2, ...);
direction:渐变的方向。可以使用角度(例如 45deg)或关键字(例如 to right、to bottom 等)来指定。
color-stop:渐变的颜色和位置。每个颜色停止点都可以指定一个颜色和一个位置(可选)。