How to Create a Simple Calculator Using HTML, CSS, and JavaScript - Complete Tutorial

Beginner 93 views Jun 28, 2026

Introduction

A calculator is a perfect beginner project to learn how HTML, CSS, and JavaScript work together. You'll build an interactive tool that can perform addition, subtraction, multiplication, and division, complete with functional buttons like Clear (C), Delete (DEL), and Equals (=).

This lightweight project uses only vanilla technologies โ€” no heavy libraries or frameworks required. Let's build it step by step.

Part 1: HTML Structure

The HTML file sets up the layout of our calculator. It includes a text entry box to act as the display and a grid container for the buttons. Each button calls a JavaScript function directly via its onclick attribute.

index.html

html
HTML
<!DOCTYPEhtml>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport"content="width=device-width, initial-scale=1.0">
 <title>Simple Calculator</title>
 <link rel="stylesheet" href="style.css">
</head>
<body>
     <div class="calculator">
        <input type="text" id="display" placeholder="0" readonly>
        <div class="buttons">
            <button onclick="clearDisplay()">C</button>
            <button onclick="deleteLast()">DEL</button>
            <button onclick="appendValue('%')">%</button>
            <button onclick="appendValue('รท')">รท</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="appendValue('+')">+</button>
            <button class="zero" onclick="appendValue('0')">0</button>
            <button onclick="appendValue('.')">.</button>
            <button onclick="calculate()">=</button>
        </div>
    </div>
 <script src="script.js"></script>
</body>
</html>

Key Points:

  • Display (#display): An tag with a readonly attribute ensures users can only interact with it using our on-screen buttons.
  • Interactivity (onclick): Every button calls a specific JavaScript function directly from the markup.
  • Layout Classes: The zero class helps us style the "0" button differently later.
  • Symbol vs. operator: The ร—, รท, and โˆ’ buttons insert nice-looking Unicode symbols into the display, not raw *, /, - characters. script.js converts them back before doing any math.

Part 2: CSS Styling

The CSS centers the calculator on the page, transforms the buttons into a neat 4-column layout using CSS Grid, and adds sleek hover and click states.

style.css

css
CSS
/* Reset & Base Styles */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "Segoe UI", Arial, sans-serif;
        }

        body {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background: #f4f6f9;
        }

        /* Calculator Container */
        .calculator {
            width: 340px;
            background: #ffffff;
            padding: 24px;
            border-radius: 20px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }

        /* Display Screen */
        #display {
            width: 100%;
            height: 65px;
            margin-bottom: 20px;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            font-size: 32px;
            text-align: right;
            padding: 12px;
            background: #f8fafc;
            color: #1e293b;
            outline: none;
        }

        /* Button Layout Grid */
        .buttons {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 12px;
        }

        button {
            height: 60px;
            border: none;
            border-radius: 12px;
            background: #3498db;
            color: #ffffff;
            font-size: 22px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        /* Interaction Effects */
        button:hover {
            background: #2980b9;
        }

        button:active {
            transform: scale(0.95);
        }

        /* Make the "0" button span two columns */
        .zero {
            grid-column: span 2;
        }

Key Points:

  • Flexbox Centering: display: flex on the body positions the app in the center of the browser window.
  • CSS Grid: grid-template-columns: repeat(4, 1fr) builds an even 4-column matrix.
  • grid-column: span 2: Stretches the "0" button to fill two grid spaces seamlessly.

Part 3: JavaScript Functionality

This script reads button presses, dynamically updates the input display text, and evaluates the resulting math expression.

script.js

javascript
JS
// Target the calculator display screen
        const display = document.getElementById("display");

        function appendValue(value) {
            display.value += value;
        }

        function clearDisplay() {
            display.value = "";
        }

        function deleteLast() {
            display.value = display.value.slice(0, -1);
        }

        function toEvaluableExpression(rawExpression) {
            return rawExpression
                .replace(/ร—/g, "*")
                .replace(/รท/g, "/")
                .replace(/โˆ’/g, "-");
        }

        function calculate() {
            if (display.value.trim() === "") {
                return;
            }
            try {
                const expression = toEvaluableExpression(display.value);
                const result = Function('"use strict"; return (' + expression + ')')();
                display.value = Number.isFinite(result)
                    ? parseFloat(result.toFixed(10))
                    : "Error";
            } catch (error) {
                display.value = "Error";
            }
        }

Key Points:

  • appendValue(): Concatenates characters directly to the input string, including the display-friendly ร—, รท, and โˆ’ symbols.
  • toEvaluableExpression(): Fixes the original bug โ€” eval()/Function() don't understand ร— or รท. Note that the browser decodes the HTML entity in the onclick attribute, so the display holds the real Unicode character โ€” the regex must match ร— itself, not the entity text.
  • slice(0, -1): Efficiently trims the final character off a string (our delete operation).
  • try...catch: Protects the app from crashing if a user types a broken formula (like 5++3); it shows "Error" instead.

Complete Project Structure

text
TXT
calculator/
โ”œโ”€โ”€ index.html
โ”œโ”€โ”€ style.css
โ””โ”€โ”€ script.js

How to Use

  1. Save these three files inside a single folder, and double-click index.html to open it in your browser.
  2. Click the numbers to build your math expression.
  3. Use the math operators (+, โˆ’, ร—, รท) to structure calculations.
  4. Hit = to display your final calculation result.
  5. Hit C to reset the calculator, or DEL to erase just the last character.

Conclusion

Congratulations! You've just built a fully working, stylish web calculator. This beginner project effectively highlights the core roles of front-end development:

  • HTML handles structural skeletons and binds event triggers.
  • CSS manages responsive grids, spacing, alignment, and animations.
  • JavaScript rules logic, user actions, and data mutation.

Technologies Used

HTML5 CSS3 JavaScript

Live Output

See the project in action below. This is the live preview of the code you just learned.

Output Preview