Build a Calculator using HTML, CSS, and JavaScript
Features:
- Basic arithmetic: Add, Subtract, Multiply, Divide
- Responsive layout
- Clickable buttons
- Keyboard input (optional)
Folder Structure:
calculator/
├── index.html
├── style.css
└── script.js
1. HTML – Calculator Layout (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>JavaScript Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="calculator">
<input type="text" id="display" disabled />
<div class="buttons">
<button onclick="clearDisplay()">C</button>
<button onclick="appendValue('/')">/</button>
<button onclick="appendValue('*')">*</button>
<button onclick="deleteLast()">⌫</button>
<button onclick="appendValue('7')">7</button>
<button onclick="appendValue('8')">8</button>
<button onclick="appendValue('9')">9</button>
<button onclick="appendValue('-')">-</button>
<button onclick="appendValue('4')">4</button>
<button onclick="appendValue('5')">5</button>
<button onclick="appendValue('6')">6</button>
<button onclick="appendValue('+')">+</button>
<button onclick="appendValue('1')">1</button>
<button onclick="appendValue('2')">2</button>
<button onclick="appendValue('3')">3</button>
<button onclick="calculate()">=</button>
<button onclick="appendValue('0')">0</button>
<button onclick="appendValue('.')">.</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
2. CSS – Styling the Calculator (style.css)
body {
font-family: Arial, sans-serif;
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
background: #f0f0f0;
}
.calculator {
border-radius: 12px;
overflow: hidden;
box-shadow: 0 0 15px rgba(0,0,0,0.2);
background: #fff;
}
#display {
width: 100%;
font-size: 2rem;
padding: 20px;
text-align: right;
border: none;
outline: none;
background: #222;
color: #fff;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
}
button {
font-size: 1.5rem;
padding: 20px;
border: 1px solid #ddd;
background: #f9f9f9;
cursor: pointer;
}
button:hover {
background: #e0e0e0;
}
3. JavaScript – Functionality (script.js)
let display = document.getElementById("display");
function appendValue(val) {
display.value += val;
}
function clearDisplay() {
display.value = "";
}
function deleteLast() {
display.value = display.value.slice(0,-1);
}
function calculate() {
try {
display.value = eval(display.value);
} catch {
display.value = "Error";
}
}
Note: eval() is used here for simplicity. In real apps, use a safe math parser like math.js.