css日历制作教程
基础日历结构
使用HTML创建一个简单的日历框架,包含星期标题和日期格子。以下是一个基础的HTML结构示例:
<div class="calendar">
<div class="header">
<span class="month">January 2023</span>
</div>
<div class="weekdays">
<div>Sun</div>
<div>Mon</div>
<div>Tue</div>
<div>Wed</div>
<div>Thu</div>
<div>Fri</div>
<div>Sat</div>
</div>
<div class="days">
<div class="empty"></div>
<div>1</div>
<div>2</div>
<!-- 更多日期... -->
</div>
</div>
日历样式设计
通过CSS为日历添加基本样式,包括容器、星期栏和日期的布局与颜色:

.calendar {
width: 300px;
border: 1px solid #ddd;
font-family: Arial, sans-serif;
}
.header {
background: #4285f4;
color: white;
padding: 10px;
text-align: center;
}
.weekdays {
display: grid;
grid-template-columns: repeat(7, 1fr);
background: #f1f1f1;
padding: 5px 0;
}
.weekdays div {
text-align: center;
}
.days {
display: grid;
grid-template-columns: repeat(7, 1fr);
gap: 5px;
padding: 5px;
}
.days div {
height: 30px;
display: flex;
align-items: center;
justify-content: center;
}
.days div:hover {
background: #e9e9e9;
cursor: pointer;
}
.empty {
background: transparent;
}
动态日期生成
结合JavaScript动态生成日历日期,自动计算当月天数及起始星期:

function generateCalendar(year, month) {
const firstDay = new Date(year, month, 1).getDay();
const daysInMonth = new Date(year, month + 1, 0).getDate();
let html = '';
for (let i = 0; i < firstDay; i++) {
html += '<div class="empty"></div>';
}
for (let i = 1; i <= daysInMonth; i++) {
html += `<div>${i}</div>`;
}
document.querySelector('.days').innerHTML = html;
}
// 调用示例:生成2023年1月日历
generateCalendar(2023, 0);
响应式布局优化
通过媒体查询使日历适应不同屏幕尺寸:
@media (max-width: 600px) {
.calendar {
width: 100%;
}
.days div {
height: 25px;
font-size: 14px;
}
}
高级交互效果
添加当前日期高亮和事件标记功能:
.current-day {
background: #4285f4;
color: white;
border-radius: 50%;
}
.has-event {
position: relative;
}
.has-event::after {
content: '';
position: absolute;
bottom: 2px;
left: 50%;
transform: translateX(-50%);
width: 4px;
height: 4px;
background: red;
border-radius: 50%;
}
// 在generateCalendar函数中添加:
const today = new Date();
if (year === today.getFullYear() && month === today.getMonth()) {
const dayElement = document.querySelector(`.days div:nth-child(${firstDay + today.getDate()})`);
dayElement.classList.add('current-day');
}






