<div class="calendar">
<h2 class="month"></h2>
<div class="days"></div>
</div>
html {
font-family: sans-serif;
font-size: 16px;
}
* {
box-sizing: border-box;
margin: 0;
}
.calendar {
width: 350px;
font-size: 1rem;
padding: 20px;
margin: 25px auto;
border: solid 1px #C2C2C2;
border-radius: 3px;
}
.days {
width: 100%;
display: grid;
grid-template-columns: repeat(7, 1fr);
}
.space {
width: calc(100% / 7);
}
.day, .calendar-header, .month {
text-align: center;
}
.month {
width: 100%;
font-size: 1.4em;
padding: 1rem 0 1.5rem 0;
font-weight: 700;
}
.day, .calendar-header {
width: 100%;
padding-bottom: 100%;
position: relative;
}
.day-number, .day-day {
font-size: 1em;
position: absolute;
top: calc(0% + 5px);
left: calc(0% + 5px);
width: calc(100% - 10px);
height: calc(100% - 10px);
display: flex;
align-items: center;
justify-content: center;
}
.day-day {
color: #5B5B64;
}
.selected .day-number {
border-radius: 50%;
background: #92CFFF;
border: solid 2px #008FFF;
}
// DOM elements
const $days = document.querySelector('.days');
const $month = document.querySelector('.month');
/** START AND END DATES OF MONTH **/
const startDate = new Date();
startDate.setDate(1);
const endDate = new Date();
endDate.setMonth(endDate.getMonth() + 1);
endDate.setDate(0);
/** CURRENT DATE **/
const now = new Date();
/*********************************/
// Array with length equal to number of days in each month
// Note: each array element is undefined
const days = Array.from( { length: endDate.getDate() } );
// Assign an object to the element representing today's day
// The element is at the index current day minus 1 due to zero-base indexing
days[now.getDate() - 1 ] = { current: true };
// Array with length equal to the number of days from a
// Monday to the Day of the first of the month
// Example: if the month starts on a Wednesday then
// there are two days from Monday to Wednesday, which is Monday and Tuesday
// These spaces will be empty
const monthBeginSpaces = Array.from({length: startDate.getDay() === 0 ? 6 : startDate.getDay() - 1});
// Create the HTML for days, spaces, and days of the week at the top
const dayNodes = days.map((day, index) => {
return `<div class="day ${ day ? "selected" : "" }"><span class="day-number">${index + 1}</span></div>`;
}).join('');
const beginSpacesNodes = monthBeginSpaces.map(space => {
return `<div class="space"></div>`;
}).join('');
const daysOfWeekNodes = ['M', 'T', 'W', 'T', 'F', 'S', 'S'].map(day => {
return `<div class="calendar-header"><span class="day-day">${day}</span></div>`;
}).join('');
// Insert the HTML into existing DOM elements
$days.innerHTML = daysOfWeekNodes + beginSpacesNodes + dayNodes;
$month.textContent = (new Intl.DateTimeFormat('en-US', {month: 'long', year: 'numeric'})).format(startDate);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.