Sure! Below is a simple HTML code for a basic calculator. It includes buttons for numbers 0-9, basic operations (addition, subtraction, multiplication, division), and equals functionality. You can copy and paste this code into an HTML file and open it in your web browser to use the calculator.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Calculator</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f2f2f2;
}
#calculator {
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
input[type="text"] {
width: 100%;
height: 40px;
font-size: 2em;
text-align: right;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 5px;
padding: 5px;
}
button {
width: 23%;
height: 60px;
font-size: 1.5em;
margin: 1%;
border: none;
border-radius: 5px;
background-color: #4CAF50;
color: white;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div id="calculator">
<input type="text" id="result" disabled>
<div>
<button onclick="clearResult()">C</button>
<button onclick="appendToResult('/')">/</button>
<button onclick="appendToResult('*')">*</button>
<button onclick="appendToResult('-')">-</button>
</div>
<div>
<button onclick="appendToResult('7')">7</button>
<button onclick="appendToResult('8')">8</button>
<button onclick="appendToResult('9')">9</button>
<button onclick="appendToResult('+')">+</button>
</div>
<div>
<button onclick="appendToResult('4')">4</button>
<button onclick="appendToResult('5')">5</button>
<button onclick="appendToResult('6')">6</button>
<button onclick="calculateResult()">=</button>
</div>
<div>
<button onclick="appendToResult('1')">1</button>
<button onclick="appendToResult('2')">2</button>
<button onclick="appendToResult('3')">3</button>
</div>
<div>
<button onclick="appendToResult('0')">0</button>
</div>
</div>
<script>
function appendToResult(value) {
document.getElementById('result').value += value;
}
function clearResult() {
document.getElementById('result').value = '';
}
function calculateResult() {
const resultField = document.getElementById('result');
try {
resultField.value = eval(resultField.value);
} catch (error) {
resultField.value = 'Error';
}
}
</script>
</body>
</html>
How to Use:
- Copy the code above.
- Paste it into a text file and save it with a
.html extension (e.g., calculator.html).
- Open the file in a web browser.
- Use the calculator by clicking the buttons!
Please note that using eval() is generally discouraged for handling user-input calculations due to security concerns, but for simple educational purposes like this, it is commonly used in small applications.