gpt-3.5-turbo-0613· OpenAI WildChat-4.8M (AI2)
Write me a calculator with Css and html
- User
Write me a calculator with Css and html
- Assistant
Sure, here's an example of a simple calculator using HTML and CSS:
HTML code:
<!DOCTYPE html> <html> <head> <title>Calculator</title> <link rel="stylesheet" type="text/css" href="calc_style.css"> </head> <body> <div class="calculator"> <input type="text" id="result" readonly> <table> <tr> <td><button onclick="clearDisplay()">C</button></td> <td><button onclick="backspace()"><</button></td> <td><button onclick="insertValue('/')">÷</button></td> <td><button onclick="insertValue('7')">7</button></td> <td><button onclick="insertValue('8')">8</button></td> <td><button onclick="insertValue('9')">9</button></td> </tr> <tr> <td><button onclick="insertValue('*')">x</button></td> <td><button onclick="insertValue('4')">4</button></td> <td><button onclick="insertValue('5')">5</button></td> <td><button onclick="insertValue('6')">6</button></td> <td><button onclick="insertValue('-')">-</button></td> </tr> <tr> <td><button onclick="insertValue('+')">+</button></td> <td><button onclick="insertValue('1')">1</button></td> <td><button onclick="insertValue('2')">2</button></td> <td><button onclick="insertValue('3')">3</button></td> <td rowspan="2"><button onclick="calculate()" id="equal">=</button></td> </tr> <tr> <td colspan="2"><button onclick="insertValue('0')">0</button></td> <td><button onclick="insertValue('.')">.</button></td> </tr> </table> </div> <script src="calc_script.js"></script> </body> </html>CSS code (calc_style.css):
* { box-sizing: border-box; padding: 0; margin: 0; } body { background-color: #f7f7f7; font-family: Arial, sans-serif; } .calculator { width: 300px; margin: 20px auto; background-color: #ddd; border-radius: 5px; text-align: center; padding: 20px; } input[type="text"] { width: 100%; height: 40px; margin-bottom: 20px; font-size: 18px; text-align: right; padding-right: 10px; } table { margin: 0 auto; } button { width: 60px; height: 40px; font-size: 18px; margin: 5px; border-radius: 5px; border: none; background-color: #f2f2f2; cursor: pointer; } button:hover { background-color: #e0e0e0; } #equal { height: 86px; font-size: 20px; }JavaScript code (calc_script.js):
function insertValue(value) { document.getElementById('result').value += value; } function clearDisplay() { document.getElementById('result').value = ''; } function backspace() { let result = document.getElementById('result').value; document.getElementById('result').value = result.slice(0, -1); } function calculate() { let result = document.getElementById('result').value; if (result) { try { document.getElementById('result').value = eval(result); } catch (error) { document.getElementById('result').value = 'Error'; } } }Save the HTML code as "index.html", the CSS code as "calc_style.css", and the JavaScript code as "calc_script.js". Then open "index.html" in your web browser to see the calculator in action.