Build a Simple Calculator with HTML, CSS & JavaScript
In this tutorial, we'll build a fully functional calculator from scratch. This is a perfect project for beginners to practice HTML structure, CSS styling, and basic JavaScript logic.
What we're building: A calculator with number buttons (0-9), operators (+, -, ×, ÷), equals (=), and clear (C) functions.
Step 1: HTML Structure
First, create the basic HTML structure for our calculator.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Simple Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="calculator">
<input type="text" class="display" readonly>
<div class="buttons">
<button>7</button>
<button>8</button>
<button>9</button>
<button>+</button>
<!-- Add more buttons here -->
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Step 2: CSS Styling
Make it look like a real calculator with CSS.
.calculator {
width: 300px;
margin: 50px auto;
border: 2px solid #333;
border-radius: 10px;
padding: 20px;
background: #f5f5f5;
}
.display {
width: 100%;
height: 50px;
font-size: 24px;
text-align: right;
margin-bottom: 15px;
padding: 10px;
box-sizing: border-box;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
button {
height: 50px;
font-size: 18px;
border: none;
border-radius: 5px;
cursor: pointer;
background: white;
}
button:hover {
background: #ddd;
}
Step 3: JavaScript Logic
Add functionality to make the calculator work.
// Get display element
const display = document.querySelector('.display');
// Add click event to all buttons
document.querySelectorAll('.buttons button').forEach(button => {
button.addEventListener('click', function() {
const value = this.textContent;
if (value === 'C') {
// Clear display
display.value = '';
} else if (value === '=') {
// Calculate result
try {
display.value = eval(display.value);
} catch {
display.value = 'Error';
}
} else {
// Append value to display
display.value += value;
}
});
});
What You'll Learn
- ✅ HTML structure for web apps
- ✅ CSS Grid for button layouts
- ✅ JavaScript event handling
- ✅ Basic calculator logic
- ✅ DOM manipulation
🚀 Take It Further
Challenge yourself: Add keyboard support, a backspace button, or a dark mode toggle!
Comments
Post a Comment