31
loading...
This website collects cookies to deliver better user experience
div
s containing the icons inside the container.<div class="container">
<div class="sun sun-logo">
<i class="fas fa-sun"></i>
</div>
<div class="moon moon-logo">
<i class="fas fa-moon"></i>
</div>
</div>
.container{
position: relative;
}
.sun, .moon{
font-size: 10rem;
width: fit-content;
height: fit-content;
}
.moon{
position: absolute;
inset: 0;
}
relative
and the moon container position to be absolute
because we will position the moon icon in the same position as that of the sun icon.top: 0;
bottom: 0;
left: 0;
and right: 0;
you can use inset: 0;
to get the same result. It works!height
and width
of the sun and the moon container to fit-content
. What this will do is, it will set the height and width of the container to match the height and width of the content inside it.font-size
of the icon..moon-logo{
opacity: 0;
transform: translateY(20%) rotateZ(50deg);
}
translateY(20%)
declaration will offset the moon icon down along the Y-axis by 20% of the height of it's parent element.rotateZ(50deg)
declaration will rotate the moon icon along the Z-axis by 50 degrees..sun-logo{
opacity: 1;
transform: translateY(0) rotateZ(0deg);
}
.animate-sun{
opacity: 0;
transform: translateY(20%) rotateZ(100deg);
color: aliceblue;
}
.animate-moon{
opacity: 1;
transform: translateY(0%) rotateZ(0deg);
color: aliceblue;
}
black
, so if you want to change the color of the icon, then define its color
property.transition
property yet, so how will it transition from one state to another? Yeah, that's the only thing left to do in CSS part..moon-logo{
opacity: 0;
transform: translateY(20%) rotateZ(50deg);
transition: all 1s ease-out;
}
.sun-logo{
opacity: 1;
transform: translateY(0) rotateZ(0deg);
transition: all 1s ease-out;
}
body{
transition: background-color 1s;
}
.dark{
background-color: black;
}
background-color
of the body
when the transition of the icons will happen.toggle
the classes on click
event.document.querySelector(".container").addEventListener("click", () => {
document.querySelector(".sun-logo").classList.toggle("animate-sun");
document.querySelector(".moon-logo").classList.toggle("animate-moon");
document.querySelector("body").classList.toggle("dark");
})
eventListener
to the container element so that when we click on the container, it will toggle the CSS classes for respective elements.classList
of an element, toggle
function will add the CSS class to the classList
of the respective element.classList
of the element, it will remove it.classList
is actually a DOMTokenList
but we will not go into the specifics of it.