Home/Blog/Web Development/How to build a simple HTML CSS JavaScript calculator
Home/Blog/Web Development/How to build a simple HTML CSS JavaScript calculator

How to build a simple HTML CSS JavaScript calculator

8 min read
May 08, 2025
content
Understanding HTML, CSS, and JavaScript
Structuring the calculator with HTML
Styling the calculator with CSS
Adding functionality to the calculator with JavaScript
Building HTML CSS JavaScript calculator
The HTML foundation for a simple calculator
Step 1: Setting up the document structure
Explanation
Step 2: Creating the calculator container
Explanation
CSS styling for a professional and responsive calculator UI
Step 1: Styling the body
Step 2: Styling the calculator container
Step 3: Styling the input field section
Step 4: Styling the buttons section
Step 5: Adding responsiveness with media query
JavaScript for calculator logic: Handling input and operations
Explanation
Wrapping up and next steps

Key takeaways:

  • Building a simple calculator is a great way to practice integrating HTML, CSS, and JavaScript in a real project.

  • HTML structures the layout, CSS enhances the design, and JavaScript adds interactivity.

  • Start with the HTML structure, apply CSS for styling, and then add JavaScript to make it functional.

What if you could create your own from scratch using HTML, CSS, and JavaScript?

Building a calculator is a great beginner-friendly project that introduces essential web development concepts while helping you gain hands-on experience structuring, styling, and adding interactivity to a web page.

In this step-by-step tutorial, we’ll guide you through building a fully functional calculator, from designing its interface to making it interactive. You’ll learn how these technologies work together and develop practical coding skills that can be applied to more complex web applications. By the end, you’ll have a sleek, user-friendly calculator that responds to user input like a real one.

Let’s dive in and start coding!

Before we start coding, let’s break down the three essential technologies that power our calculator:

Understanding HTML, CSS, and JavaScript#

Structuring the calculator with HTML#

HTML (HyperText Markup Language) is the backbone of every web page, defining its structure and content. It uses tags to create headings, paragraphs, buttons, input fields, and more. Think of HTML as the framework of a building—it provides the skeleton, but without styling or functionality, it remains plain and unappealing.

For our calculator, HTML will define the layout, including:

  • The display screen where results appear

  • Number and operator buttons

  • A clear/reset button for deleting inputs

Each of these elements will be represented using HTML tags, forming the basic structure of our application.

Styling the calculator with CSS#

CSS (Cascading Style Sheets) is responsible for designing and styling the calculator. Without CSS, a web page would look like a plain text block. With CSS, we can apply colors, align elements, add spacing, and make the calculator responsive across different screen sizes.

In our calculator, CSS will be used to:

  • Style the buttons for a modern and interactive feel

  • Organize the layout with grids or Flexbox for a structured appearance

  • Add hover effects and smooth transitions to improve user experience

With just a few lines of CSS, we can transform a basic HTML structure into a visually appealing, user-friendly calculator.

Adding functionality to the calculator with JavaScript#

While HTML provides the structure and CSS enhances the appearance, JavaScript is the magic that makes the calculator interactive. JavaScript is a powerful programming language that allows us to control web page behavior and handle user interactions dynamically.

For our calculator, JavaScript will be responsible for:

  • Detecting button clicks and capturing user input

  • Performing arithmetic operations like addition, subtraction, multiplication, and division

  • Displaying results dynamically and handling errors like division by zero

Without JavaScript, the calculator would just have a static design. By writing a few event listeners and functions, we’ll make it functional, allowing users to perform real calculations effortlessly.

To understand in-depth concepts of HTML, CSS, and JavaScript, don’t forget to have a look at Educative’s course:

Learn HTML, CSS, and JavaScript from Scratch

Cover
Learn HTML, CSS, and JavaScript from Scratch

This course will teach you the fundamentals of creating web applications, from the basics of creating web pages with HTML, stylizing content with CSS, all the way to building interactivity into a page using JavaScript in the browser. Instead of watching tedious videos and wondering how to translate those videos into real code, you'll be practicing what you learn through interactive, test-based exercises within minutes. Along the way, you'll be able to produce functional modules, including an image carousel and a to-do list application. No prior knowledge is needed.

10hrs
Beginner
41 Challenges
19 Quizzes

Now that we’ve covered the core technologies behind the calculator, it’s time to start coding.

Building HTML CSS JavaScript calculator#

The HTML foundation for a simple calculator#

We will start with a simple structure for the calculator. Let’s follow a step-by-step approach to this.

Step 1: Setting up the document structure#

We start by giving the calculator a name in the <title> tag in the browser tab.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Educative’s Calculator</title>
<link rel="stylesheet" href="styles.css">
</head>
Setting up the document structure

Explanation#

  • Line 1: We declare the document as an HTML5 document.

  • Line 2: We set the language to English, which aids accessibility and SEO.

  • Lines 3–8: We define the head that contains metadata.

    • Line 6: We call our calculator “Educative’s Calculator” within the <title> tag.

    • Line 7: We link our stylesheet styles.css to the main HTML file.

Step 2: Creating the calculator container#

This is where the actual fun begins! We use a div with a class name calculator as the main container for the entire calculator.

<body>
<div class="calculator">
<div class="display">
<input type="text" id="result" disabled>
</div>
<div class="buttons">
<button>7</button>
<button>8</button>
<button>9</button>
<button>/</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>*</button>
<button>1</button>
<button>2</button>
<button>3</button>
<button>-</button>
<button>0</button>
<button>.</button>
<button>=</button>
<button>+</button>
<button>C</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Creating the calculator container
Explanation#
  • Line 2: The <div class="calculator"> is the parent div for all calculator elements.

  • Lines 3–5: We define an <input> element for displaying the user input and results. The disabled attribute ensures users cannot type manually.

  • Lines 6–24: We define a section that contains the buttons for numbers (09), operators (+, -, *, /), the decimal point (.), the equal sign (=), and a clear button (C). Each <button> element represents a clickable calculator button.

Let’s look at the HTML structure that we have created so far:

CSS styling for a professional and responsive calculator UI#

CSS transforms the plain HTML structure into a visually pleasing and user-friendly calculator. Let’s follow a step-by-step approach to this.

Step 1: Styling the body#

The application body is styled to center the calculator and apply a background color.

body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
Styling the body

In the code above, we do the following to style the body:

  • Line 2: We use font-family to set sans-serif font for all text.

  • Line 3: We use background-color to set a light gray background.

  • Line 4: We use Flexbox (display: flex) to center the calculator horizontally and vertically.

Step 2: Styling the calculator container#

The main calculator div is styled with a shadow, rounded corners, and a fixed width.

.calculator {
background: #fff;
border-radius: 10px;
box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2);
width: 90%;
max-width: 300px;
padding: 10px 10px 0px 10px;
}
Styling the calculator container

In the code above, we do the following to style the calculator container:

  • Line 2: We use background to set the calculator background to white.

  • Line 3: We use border-radius to create rounded corners for the container.

  • Line 4: We use box-shadow to add a shadow for depth.

Step 3: Styling the input field section#

The input field section is styled to look like a traditional calculator screen.

.display input {
width: 100%;
height: 60px;
border: none;
text-align: right;
font-size: 24px;
padding: 10px;
box-sizing: border-box;
border-bottom: 2px solid #ccc;
}
Styling the input field section

In the code above, we do the following to style the input field section:

  • Line 2: We use width: 100% to ensure the display spans the width of the calculator.

  • Line 5: We use text-align: right to align numbers and results to the right, like a standard calculator.

  • Line 6: We use font-size: 24px to make text easily readable.

Step 4: Styling the buttons section#

The buttons are arranged in a grid layout for symmetry.

.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 5px;
padding: 10px 0;
}
button {
height: 60px;
border: none;
font-size: 20px;
cursor: pointer;
background-color: #f1f1f1;
border-radius: 5px;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #ddd;
}
button:nth-child(17) {
background-color: #f76c6c;
color: white;
}
Styling the buttons section

In the code above, we do the following to style the buttons section:

  • Line 3: We use grid-template-columns: repeat(4, 1fr) to create a 4-column grid for buttons.

  • Line 4: We use gap: 5px to add spacing between buttons.

  • Lines 18–20: We use hover effect on buttons to add interactivity with a color change.

  • Lines 22–25: The “C” button (nth-child(17)) is styled in red to indicate its importance.

Step 5: Adding responsiveness with media query#

To ensure the calculator works well on smaller screens, we use a media query to adjust the layout and element sizes for devices with a screen width of 480px or less.

/* Media query for smaller screens (e.g., mobile devices) */
@media (max-width: 480px) {
.calculator {
width: 100%;
margin: 10px;
padding: 10px;
}
button {
height: 50px;
font-size: 18px;
}
.display input {
height: 50px;
font-size: 20px;
}
.buttons {
gap: 3px;
padding: 10px 0;
}
}
Making the styling responsive for different screens

In the code above, the following adjustments are made to enhance the calculator’s usability on small screens:

  • Lines 3–7: We create a .calculator function.

    • Line 4: We use .calculator { width: 100%; } to ensure the calculator spans the full width of smaller devices, making it easier to use.

    • Line 5: We have added a margin around the calculator .calculator { margin: 10px; } for breathing space and better aesthetics.

  • Lines 9–12: We use button { height: 50px; font-size: 18px; } to reduce the button height and font size, ensuring they fit comfortably on smaller screens while remaining functional.

  • Lines 14–17: We use .display input { height: 50px; font-size: 20px; }: to adjust the display field’s height and font size to maintain readability without wasting space.

  • Lines 19–22: Lastly, we have reduced the spacing between buttons using .buttons { gap: 3px; } to optimize space usage while maintaining a clean layout.

By incorporating this media query, the calculator layout becomes fully responsive, ensuring a seamless experience on devices of all sizes, including mobile phones.

Let’s now integrate the CSS styles with the HTML structure that we have created.

The CSS styles created above ensure a responsive, professional design that adapts to different screen sizes.

Looking to design a personalized digital resume? Try the “Creating an Online CV with HTML and CSS” project to learn how to craft an interactive online CV using HTML for a polished and unique presentation.

JavaScript for calculator logic: Handling input and operations#

JavaScript powers the calculator by handling user input and processing calculations.

const resultInput = document.getElementById("result");
let currentInput = "";
document.querySelectorAll(".buttons button").forEach(button => {
button.addEventListener("click", () => {
const value = button.textContent;
if (value === "C") {
currentInput = "";
} else if (value === "=") {
try {
currentInput = eval(currentInput).toString();
} catch {
currentInput = "Error";
}
} else {
currentInput += value;
}
resultInput.value = currentInput;
});
});
Adding interactivity with JavaScript

Explanation#

  • Line 1: We get a reference of the <input> field where results are displayed.

  • Line 2: We store the user’s input as a string for processing.

  • Lines 4–6: We capture button clicks and retrieve the button’s text content.

  • Lines 8–9: We clear the input if “C” is pressed.

  • Lines 10–15: If “=” is pressed, we evaluate the mathematical expression using the eval() method. An error is displayed if the input contains invalid characters or an incomplete expression.

The eval() function is convenient but insecure. A user entering JavaScript code instead of a mathematical expression could execute malicious input. A safer alternative is to use a math parser library like math.js.

  • Lines 16–18: For other buttons, we append their value to the input string.

  • Line 20: We update the value of the referenced <input> field with the new evaluated value.

Let’s integrate this JavaScript script to make our static calculator interactive.

Congratulations, we have finally created a calculator using only HTML, CSS, and JavaScript.

Want to build an SEO-friendly real-world application with HTML? Try this project: Build a Microblogging App Using PHP, HTML, JavaScript, and CSS.

Wrapping up and next steps#

Building a calculator using HTML, CSS, and JavaScript is a foundational project for aspiring web developers. It introduces you to the essential concepts of structuring web content, styling interfaces, and creating interactive applications.

Following this guide, you’ve built a working calculator and strengthened your HTML, CSS, and JavaScript skills. Now, challenge yourself—can you add more features like a backspace button or keyboard support?

Frequently Asked Questions

Can I use a JavaScript library to build the calculator?

Yes, libraries like React or Vue.js can simplify the process, especially for larger projects. However, building a calculator without libraries helps you understand the core concepts.

What is the purpose of the eval() function in JavaScript, and is it safe?

The eval() function evaluates JavaScript code as a string, allowing us to perform arithmetic calculations from user input. However, it can be unsafe if user input is not properly sanitized, as it could potentially execute malicious code. Consider parsing and processing the input manually or using safer libraries for better security.

What is the difference between disabled and readonly for the input field?

  • disabled: Prevents user interaction with the input field and visually indicates it’s inactive.

  • readonly: Prevents editing the input field but allows users to focus and copy the text.

How do I deploy an HTML, CSS, or JavaScript app?

You can deploy an HTML, CSS, or JavaScript app using free services like:

  • GitHub Pages
  • Netlify
  • Vercel
  • etc.

How do you put HTML, CSS, and JavaScript together?

To combine HTML, CSS, and JavaScript in a project, you typically use HTML as the structure, CSS for styling, and JavaScript for interactivity. The most common approach is linking separate files: HTML includes the content, a <link> tag in the <head> references an external CSS file (styles.css), and a <script> tag, usually placed before the closing </body>, links an external JavaScript file (script.js). Alternatively, CSS can be written inside a <style> tag in the <head>, and JavaScript can be placed within a <script> tag inside the HTML file. Inline styles and JavaScript within element attributes are also possible but generally discouraged for maintainability and separation of concerns.

How do you make an app using HTML, CSS, and JavaScript?

To create an app using HTML, CSS, and JavaScript, you first design the user interface with HTML, style it with CSS, and add interactivity with JavaScript. Structure your files as index.html, styles.css, and script.js for a simple web app, linking them appropriately. Use frameworks like Bootstrap for styling and libraries like jQuery or vanilla JavaScript for dynamic behavior. Consider using a front-end framework like React, Vue, or Angular for a more advanced app. If you need backend functionality, integrate Node.js with Express or use Firebase. Tools like Cordova or Progressive Web Apps (PWAs) allow deployment across different platforms to make it a mobile app.

How do you start an HTML CSS JavaScript project?

To start an HTML, CSS, and JavaScript project, first, create a project folder, and inside it, create three files: index.html for structure, styles.css for styling, and script.js for interactivity. In index.html, set up the basic structure using <!DOCTYPE html>, <html>, <head>, and <body>. Link styles.css in the <head> using <link> and script.js (before using <script>). Use a code editor like VS Code for a better development experience. Optionally, initialize a Git repository for version control and use a local server (like Live Server extension in VS Code) for real-time preview.

How do you make calculations in JavaScript?

In JavaScript, you can perform calculations using arithmetic operators like + (addition), - (subtraction), * (multiplication), / (division), and % (modulus). You can store numbers in variables and use them in expressions. For more complex calculations, JavaScript provides the Math object, which includes methods like Math.pow(x, y) for exponentiation, Math.sqrt(x) for square root, and Math.round(x) for rounding numbers. You can also use parseFloat() or parseInt() to convert user input (from forms) into numbers before performing calculations. Example:

let a = 10, b = 5;
let sum = a + b;
let squareRoot = Math.sqrt(25);
console.log(sum); // Output: 15
console.log(squareRoot); // Output: 5

This allows you to perform basic and advanced mathematical operations efficiently in JavaScript.

What can I create with HTML, CSS, and JavaScript?

You can create various web-based applications with HTML, CSS, and JavaScript, from simple static websites to interactive and dynamic web apps. Some common projects include:

  • Personal portfolios and blogs: A static or dynamic web page showcasing your work and experiences.
  • Landing pages and business websites: Marketing sites with responsive design and interactive elements for businesses.
  • Interactive forms and surveys: Collecting user input with validation and processing.
  • Web-based games: Simple browser games using JavaScript and Canvas.
  • To-do lists and note-taking apps: Interactive applications using local storage to save data.
  • Weather apps: Fetching and displaying weather data from APIs.
  • E-commerce stores: Basic shopping cart functionalities with JavaScript.
  • Progressive web apps (PWAs): Web apps that function like native mobile apps.
  • Dashboards and data visualization: Using JavaScript libraries like Chart.js or D3.js.
  • Single-page applications (SPAs): More advanced apps using JavaScript frameworks like React or Vue.

With additional tools like Node.js, Firebase, or frameworks, you can extend the capabilities to build more complex full-stack applications.

How do you save a JavaScript file?

To save a JavaScript file, create a .js file (e.g., script.js) in a code editor and write your code. Link it to an HTML file using:

<script src="script.js"></script>

Save with “Ctrl + S” (Windows/Linux) or “Cmd + S” (Mac) and refresh the browser to see updates. For debugging, use the browser console (“F12”).


Written By:
Hamna Waseem

Free Resources