css制作课表
CSS制作课表的方法
使用CSS制作课表可以通过表格布局或Flexbox/Grid布局实现。以下是两种常见的方法:
表格布局
表格布局适合结构化的数据展示,课表通常具有固定的行和列。
<style>
.timetable {
width: 100%;
border-collapse: collapse;
}
.timetable th, .timetable td {
border: 1px solid #ddd;
padding: 8px;
text-align: center;
}
.timetable th {
background-color: #f2f2f2;
}
.timetable tr:nth-child(even) {
background-color: #f9f9f9;
}
</style>
<table class="timetable">
<tr>
<th>时间</th>
<th>周一</th>
<th>周二</th>
<th>周三</th>
<th>周四</th>
<th>周五</th>
</tr>
<tr>
<td>08:00-09:00</td>
<td>数学</td>
<td>语文</td>
<td>英语</td>
<td>物理</td>
<td>化学</td>
</tr>
</table>
Flexbox布局
Flexbox布局适合需要更灵活的设计,比如响应式课表。
<style>
.timetable-container {
display: flex;
flex-direction: column;
gap: 5px;
}
.timetable-row {
display: flex;
gap: 5px;
}
.timetable-cell {
flex: 1;
border: 1px solid #ddd;
padding: 8px;
text-align: center;
}
.timetable-header {
background-color: #f2f2f2;
font-weight: bold;
}
</style>
<div class="timetable-container">
<div class="timetable-row">
<div class="timetable-cell timetable-header">时间</div>
<div class="timetable-cell timetable-header">周一</div>
<div class="timetable-cell timetable-header">周二</div>
<div class="timetable-cell timetable-header">周三</div>
<div class="timetable-cell timetable-header">周四</div>
<div class="timetable-cell timetable-header">周五</div>
</div>
<div class="timetable-row">
<div class="timetable-cell">08:00-09:00</div>
<div class="timetable-cell">数学</div>
<div class="timetable-cell">语文</div>
<div class="timetable-cell">英语</div>
<div class="timetable-cell">物理</div>
<div class="timetable-cell">化学</div>
</div>
</div>
响应式设计
为了确保课表在移动设备上也能正常显示,可以添加媒体查询调整布局。
@media (max-width: 600px) {
.timetable-row {
flex-direction: column;
}
.timetable-cell {
width: 100%;
}
}
样式优化
可以通过CSS变量和伪类选择器进一步优化样式,比如悬停效果和斑马纹。
:root {
--primary-color: #4CAF50;
--secondary-color: #f2f2f2;
}
.timetable-cell:hover {
background-color: var(--primary-color);
color: white;
}
.timetable-row:nth-child(even) .timetable-cell:not(.timetable-header) {
background-color: var(--secondary-color);
}
动态生成课表
如果需要动态生成课表,可以结合JavaScript和CSS。以下是一个简单的示例:
const courses = [
{ time: "08:00-09:00", mon: "数学", tue: "语文", wed: "英语", thu: "物理", fri: "化学" }
];
function generateTimetable() {
const container = document.querySelector('.timetable-container');
courses.forEach(course => {
const row = document.createElement('div');
row.className = 'timetable-row';
row.innerHTML = `
<div class="timetable-cell">${course.time}</div>
<div class="timetable-cell">${course.mon}</div>
<div class="timetable-cell">${course.tue}</div>
<div class="timetable-cell">${course.wed}</div>
<div class="timetable-cell">${course.thu}</div>
<div class="timetable-cell">${course.fri}</div>
`;
container.appendChild(row);
});
}
generateTimetable();
通过以上方法,可以灵活地使用CSS制作出美观且功能完善的课表。







