In this project, I built a modern calculator that supports:
- Basic arithmetic (+, -, *, /)
- Scientific operations (sin, cos, tan, log, √, ^)
- Dark/Light mode toggle
- Responsive design for mobile devices
This blog explains the HTML structure, CSS styling, and JavaScript logic step by step.
HTML Structure:
CSS Styling
- Flexbox Centering: The calculator is centered vertically and horizontally.
- Dark/Light Mode: .color class toggles background color.
- Grid Layout: Buttons are arranged in a grid using grid-template-columns: repeat(4, 1fr).
- Responsive: Media queries resize buttons and container on mobile screens.
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#container {
box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
display: flex;
flex-direction: column;
gap: 25px;
padding: 30px;
width: 25%;
border-radius: 40px;
}
.gridbtn {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 20px;
}
1.Selecting Elementsconst input = document.getElementById("input");
const sci = document.getElementById("bottomBtn");
- input → To display numbers and results.
- sci → Reference to scientific buttons section.
2. Adding Values
Appends the clicked button value to the input field.function press(value) {
input.value += value;
}
3. Clearing Input
Resets the input field when C button is clicked.function clearInput() {
input.value = " ";
}
4. Calculating Expression
- Evaluates the expression in the input field using eval().
- If invalid input, displays “Error”.
function calculate() {
try {
input.value = eval(input.value);
} catch {
input.value = "Error";
}
}
5. Dark/Light Mode Toggle
- Toggles .color class for background change.
- Changes heading color for readability.
function toggleDark() {
document.getElementById('container').classList.toggle("color");
document.getElementsByTagName('h1')[0].classList.toggle("h1");
}
6. Scientific Mode Toggle
Shows/hides scientific buttons (sin, cos, tan, etc.)
function scientific() {
sci.style.display = sci.style.display === "none" ? "grid" : "none";
}
Thanks for reading! See you soon!