본문 바로가기
Side Project

HTML, CSS, JavaScript로 Calendar 만들기 - 1

by Brilliant_Graphite 2024. 7. 13.
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>달력</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="wrap">
        <div id="year"></div>
        <div id="month"></div>
        <div class="week">
            <div id="monday"></div>
            <div id="tuesday"></div>
            <div id="wednesday"></div>
            <div id="thursday"></div>
            <div id="friday"></div>
            <div id="saturday"></div>
            <div id="sunday"></div>  
        </div>
    </div>

    <script src="script.js"></script>
</body>
</html>

 

body {
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
}

.wrap {
    width: 300px;
    border: 1px solid #000;
    padding: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

#year, #month {
    text-align: center;
    margin: 10px 0;
    font-size: 20px;
}

.week {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    grid-gap: 5px;
}

.week div {
    width: 40px;
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid #ccc;
    box-sizing: border-box;
    margin-left: -1px;
}

 

document.addEventListener("DOMContentLoaded", function() {
    const daysOfWeek = ["일", "월", "화", "수", "목", "금", "토"];
    const today = new Date();
    const currentYear = today.getFullYear();
    const currentMonth = today.getMonth();
    
    document.getElementById("year").innerText = currentYear + "년";
    document.getElementById("month").innerText = (currentMonth + 1) + "월";
    
    const firstDay = new Date(currentYear, currentMonth, 1).getDay();
    const lastDate = new Date(currentYear, currentMonth + 1, 0).getDate();

    const daysContainer = document.querySelector(".week");
    daysContainer.innerHTML = "";  // Clear any existing content

    // Create day of week headers
    daysOfWeek.forEach(day => {
        const dayHeader = document.createElement("div");
        dayHeader.innerText = day;
        daysContainer.appendChild(dayHeader);
    });

    // Add blank days for the first week
    for (let i = 0; i < firstDay; i++) {
        const blankDay = document.createElement("div");
        daysContainer.appendChild(blankDay);
    }

    // Add days of the month
    for (let date = 1; date <= lastDate; date++) {
        const day = document.createElement("div");
        day.innerText = date;
        daysContainer.appendChild(day);
    }
});

practice.html
0.00MB
styles.css
0.00MB
script.js
0.00MB