Light/Dark Theme using Html | Css | Js
Please follow the below code and get started 💻.
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Light and Dark Theme</title>
<!-- font awesome icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" />
<!-- external css -->
<link rel="stylesheet" href="style.css">
</head>
<body class="light">
<div class="container">
<i class="fa-solid fa-sun"></i>
<i class="fa-solid fa-moon"></i>
<button class="switch-btn">
<span>Switch Theme</span>
</button>
</div>
<script src="./app.js"></script>
</body>
</html>
CSS Code
:root {
--dark: #101019;
--light: #f9f9f9;
}
*,
::after,
::before {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body.light {
background: var(--light);
}
body.dark {
background: var(--dark);
}
body {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
transition: .5s ease;
}
.container {
position: relative;
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
}
.switch-btn {
background: #007bff;
padding: .75rem 1.5rem;
color: var(--light);
outline: none;
border: none;
font-size: 1rem;
font-family: sans-serif;
cursor: pointer;
border-radius: 6px;
margin: auto;
}
.switch-btn:active {
transform: scale(0.97);
}
.fa-sun,
.fa-moon {
position: absolute;
top: 15%;
font-size: 4rem;
transition: .5s ease;
}
.fa-moon {
color: var(--light);
}
.fa-sun {
color: #f6b41a;
}
body.dark .fa-sun {
transform: translateY(-100px) rotate(90deg);
opacity: 0;
}
body.light .fa-moon {
transform: translateY(100px) rotate(90deg);
opacity: 0;
}
JavaScript Code
// selectors
const bodyEle = document.querySelector('body');
const btnEle = document.querySelector('.switch-btn');
// toggle button to switch theme
btnEle.addEventListener('click', () => {
if (bodyEle.classList[0] === 'light') {
bodyEle.classList.remove('light')
bodyEle.classList.add('dark')
}
else if (bodyEle.classList[0] === 'dark') {
bodyEle.classList.remove('dark')
bodyEle.classList.add('light')
}
})
Output
That is all! Thank you for visiting my blog.
Code by - AltafAlam Shaikh
Topic covered - toggle() in javascript, transform property in css
Technology used - Html, Css, JavaScript