在前端页面开发中,进度条是展示任务完成度、加载状态等信息的常用组件,很多时候默认的进度条样式无法满足设计需求,我们可以自己用HTML和CSS构建并定制样式。

基础进度条结构搭建
我们可以用两个嵌套的<div>标签来构建进度条的容器和进度填充部分,外层作为进度条的整体背景,内层作为实际显示的进度部分。
<div class="progress-container"> <div class="progress-fill" id="progressFill"></div> </div>
基础样式定制
通过CSS可以修改进度条的整体外观,包括高度、背景色、圆角等属性,让进度条符合设计规范。
/* 进度条容器样式 */
.progress-container {
width: 100%;
height: 20px;
background-color: #f0f0f0;
border-radius: 10px;
overflow: hidden; /* 保证填充部分不超出圆角容器 */
margin: 20px 0;
}
/* 进度填充部分样式 */
.progress-fill {
width: 0%; /* 初始进度为0 */
height: 100%;
background-color: #4CAF50;
border-radius: 10px;
transition: width 0.3s ease; /* 添加宽度变化的过渡动画 */
}动态控制进度
我们可以通过JavaScript动态修改进度填充部分的宽度,来模拟进度变化的效果。
// 获取进度填充元素
const progressFill = document.getElementById('progressFill');
let currentProgress = 0;
// 模拟进度增长的函数
function updateProgress() {
if (currentProgress >= 100) {
return;
}
currentProgress += 10;
progressFill.style.width = currentProgress + '%';
}
// 每1秒增加一次进度
setInterval(updateProgress, 1000);进阶样式定制
除了基础样式,我们还可以添加更多定制效果,比如渐变背景、条纹样式、文字提示等。
渐变背景进度条
修改<code>progress-fill</code>的背景为线性渐变,让进度条视觉效果更丰富。
.progress-fill {
width: 0%;
height: 100%;
/* 线性渐变背景 */
background: linear-gradient(to right, #4CAF50, #8BC34A);
border-radius: 10px;
transition: width 0.3s ease;
}带条纹和动画的进度条
可以添加条纹背景和流动动画,让加载状态更明显。
.progress-fill {
width: 0%;
height: 100%;
background-color: #4CAF50;
background-image: linear-gradient(
45deg,
rgba(255, 255, 255, 0.15) 25%,
transparent 25%,
transparent 50%,
rgba(255, 255, 255, 0.15) 50%,
rgba(255, 255, 255, 0.15) 75%,
transparent 75%,
transparent
);
background-size: 40px 40px;
border-radius: 10px;
transition: width 0.3s ease;
/* 条纹流动动画 */
animation: progress-stripes 2s linear infinite;
}
@keyframes progress-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}带进度文字提示
在进度条内部添加文字显示当前进度百分比,提升交互体验。
<div class="progress-container">
<div class="progress-fill" id="progressFill">
<span class="progress-text" id="progressText">0%</span>
</div>
</div>.progress-container {
width: 100%;
height: 20px;
background-color: #f0f0f0;
border-radius: 10px;
overflow: hidden;
margin: 20px 0;
position: relative;
}
.progress-fill {
width: 0%;
height: 100%;
background-color: #4CAF50;
border-radius: 10px;
transition: width 0.3s ease;
position: relative;
}
.progress-text {
position: absolute;
right: 10px;
top: 50%;
transform: translateY(-50%);
color: #fff;
font-size: 12px;
font-weight: bold;
}const progressFill = document.getElementById('progressFill');
const progressText = document.getElementById('progressText');
let currentProgress = 0;
function updateProgress() {
if (currentProgress >= 100) {
return;
}
currentProgress += 10;
progressFill.style.width = currentProgress + '%';
progressText.textContent = currentProgress + '%';
}
setInterval(updateProgress, 1000);
HTMLprogress_barstyle_customizationCSS修改时间:2026-06-05 17:56:16