Create A Calculator Using HTML, CSS & JavaScript
Here is HTML, CSS and JavaScript code to create a basic web calculator.
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="calculator">
<input type="text" id="display">
<button onclick="deleteVal()">C</button>
<button onclick="deleteChar()">CE</button>
<button onclick="add('%')">%</button>
<button onclick="add('/')">/</button>
<button onclick="add('7')">7</button>
<button onclick="add('8')">8</button>
<button onclick="add('9')">9</button>
<button onclick="add('*')">*</button>
<button onclick="add('4')">4</button>
<button onclick="add('5')">5</button>
<button onclick="add('6')">6</button>
<button onclick="add('-')">-</button>
<button onclick="add('1')">1</button>
<button onclick="add('2')">2</button>
<button onclick="add('3')">3</button>
<button onclick="add('+')">+</button>
<button onclick="add('0')">0</button>
<button onclick="add('00')">00</button>
<button onclick="add('.')">.</button>
<button onclick="calculate()" id="equal">=</button>
<script src="script.js"></script>
</div>
</body>
</html>
CSS Code:
body{
box-sizing: border-box;
margin:0;
padding:0;
display:flex;
justify-content: center;
align-items: center;
height: 100vh;
background: rgb(8,110,111);
background: linear-gradient(140deg, rgba(8,110,111,1),rgba(56,9,121,1)100%);
}
.calculator{
width: 300px;
padding: 20px;
background-color: #1f0033;
box-shadow: 0 0 10px rgba(0,0,0, 0.6);
border-radius: 10px;
}
button{
width: 50px;
height: 50px;
margin: 10px;
font-size: 20px;
border: none;
border-radius: 5px;
background-color: #a1a1a1;
cursor: pointer;
}
button:hover{
background-color: #ddd;
}
#equal:hover{
background-color: rgb(2,245,2);
}
button:active{
background-color: rgb(100,100,100);
}
#equal:active{
background-color: rgb(0,80,0);
}
#display{
width: 90%;
margin-bottom: 10px;
padding: 10px;
border: none;
border-radius: 5px;
font-size: 25px;
text-align: right;
}
JavaScript Code:
let display = document.getElementById('display');
function add(val){
display.value += val;
}
function deleteVal(){
display.value ='';
}
function deleteChar(){
display.value= display.value.slice(0,-1);
}
function calculate(){
display.value= eval(display.value);
}