Build a Calculator in JavaScript Using HTML and CSS in 2025
By Rohan Vats
Updated on Mar 07, 2025 | 13 min read | 27.6k views
Share:
For working professionals
For fresh graduates
More
By Rohan Vats
Updated on Mar 07, 2025 | 13 min read | 27.6k views
Share:
Table of Contents
Building a calculator in Javascript using HTML and CSS is a great way to learn the basics of web development while creating a practical tool. In this tutorial, we will walk through the process of building a functional calculator from scratch, using modern web technologies for the year 2025.
We’ll explore how to create the structure with HTML, style the user interface with CSS, and implement the logic with JavaScript. This project will give you hands-on experience with handling user input, performing calculations, and designing a clean, responsive layout.
Key Technologies Used:
By the end of this guide , you’ll have a fully functional calculator using JavaScript that can perform basic arithmetic operations. Whether you're just starting out or looking to enhance your skills, this project is an excellent way to dive into calculator development using HTML, CSS, and JavaScript.
Before directly going to code in HTML, CSS, and Java, let’s plan, how to build a calculator. It helps define the features, layout, and user experience, ensuring the project is organized and functional. Let’s break down the planning process into two key areas: features and functionality and wireframing and layout design.
The first step in planning the calculator is deciding on the core features. Here are the primary functionalities we need to implement for a calculator in JavaScript:
These features will give us a fully functional calculator that meets the needs of most users. Once the features are defined, it’s important to design how the calculator will look and how users will interact with it.
Wireframing involves planning the arrangement of elements like buttons and the display screen. The layout of the calculator should be intuitive and easy to use. Typically, the number buttons (0–9) are placed in a grid, with operators and special buttons like C (clear), ← (backspace), and = (equals) positioned logically for ease of use.
The display should be large enough to show input clearly and should sit at the top for easy visibility. Additionally, the layout should be responsive, ensuring the calculator works well on all screen sizes, especially mobile devices.
To begin building a calculator in JavaScript, we need to set up the project structure. This will help keep everything organized and ensure that all components of our calculator function properly together.
Check out Java Free Online Course
Here’s how to structure your project and link the necessary files.
For a clean and manageable project, use the following folder structure:
/calculator
├── index.html
├── styles.css
└── script.js
By organizing the project in this way, we ensure that the calculator using HTML, CSS, and JavaScript is easy to maintain and expand upon in the future.
Now that we have our folder structure in place, we need to link the HTML, CSS, and JavaScript files together to make the calculator work. Here’s how to do it:
1. Linking the CSS File in HTML: In your index.html file, link the styles.css file in the <head> section:
<link rel="stylesheet" href="styles.css">
2. Linking the JavaScript File: In the <body> section of index.html, add a script tag to link the script.js file:
<script src="script.js"></script>
This ensures that your JavaScript calculator will be loaded and executed after the HTML structure is ready.
Here’s how the basic HTML file should look with both the CSS and JavaScript files linked:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<!-- Calculator layout goes here -->
<script src="script.js"></script>
</body>
</html>
With the HTML, CSS, and JavaScript files properly linked, you're now ready to start building the actual calculator in JavaScript. This organization ensures that the components interact seamlessly to deliver a smooth user experience.
Learn how to build a calculator using Python
The first step in building our calculator is to create the HTML structure. HTML provides the skeleton of the calculator, which includes the display for showing results and buttons for user interaction. We'll define the layout and structure of the calculator elements.
Here’s the boilerplate code for the HTML document:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Calculator - By Upgrad</title>
<!-- Link to external CSS file for styling -->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!-- Main container for the calculator -->
<div class="calculator-container">
<!-- Display area where numbers and results are shown -->
<input type="text" id="display" class="display" disabled />
<!-- Buttons for the calculator -->
<div class="buttons">
<button class="btn clear" id="clear">C</button>
<button class="btn backspace" id="backspace">←</button>
<button class="btn operator" id="divide">/</button>
<button class="btn operator" id="multiply">*</button>
<button class="btn" id="7">7</button>
<button class="btn" id="8">8</button>
<button class="btn" id="9">9</button>
<button class="btn operator" id="subtract">-</button>
<button class="btn" id="4">4</button>
<button class="btn" id="5">5</button>
<button class="btn" id="6">6</button>
<button class="btn operator" id="add">+</button>
<button class="btn" id="1">1</button>
<button class="btn" id="2">2</button>
<button class="btn" id="3">3</button>
<button class="btn equals" id="equals">=</button>
<button class="btn" id="0">0</button>
<button class="btn" id="decimal">.</button>
</div>
</div>
<!-- Link to external JavaScript file for functionality -->
<script src="script.js"></script>
</body>
</html>
Source: Calculator html
Explanation of HTML:
Now, let's add CSS to style our calculator. We'll define the general layout, button styles, and the look of the display. The goal is to make the calculator visually appealing and easy to use.
/* Resetting default margin and padding for a clean slate */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Body and overall page styling */
body {
/* Font for the whole body */
background-color: #f4f4f4; /* Light gray background for the page */
display: flex;
justify-content: center;
align-items: center;
height: 100vh; /* Full viewport height */
margin: 0;
}
/* Container styling for the calculator */
.calculator-container {
width: 320px; /* Fixed width for the calculator */
background-color: #fff; /* White background for the calculator */
border-radius: 10px; /* Rounded corners for a modern look */
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2); /* Soft shadow effect */
padding: 20px;
display: flex;
flex-direction: column;
align-items: center;
gap: 20px; /* Space between elements */
}
/* Display area styling */
.display {
width: 100%; /* Full width of the container */
height: 50px; /* Set height of the display area */
font-size: 24px; /* Font size for numbers */
text-align: right; /* Right-align the text in the display */
padding: 10px;
background-color: #f9f9f9; /* Light background for the display */
border: 1px solid #ccc; /* Border around the display */
border-radius: 5px; /* Rounded corners for the display */
margin-bottom: 20px; /* Space below the display */
color: #333; /* Dark text color */
}
/* Button layout in a grid (4 columns for calculator layout) */
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr); /* 4 equal-width columns */
grid-gap: 10px; /* Gap between buttons */
width: 100%;
}
/* General button styling */
.btn {
background-color: #f0f0f0; /* Light gray background */
border: 1px solid #ccc; /* Border around each button */
border-radius: 5px; /* Rounded corners for buttons */
font-size: 18px; /* Font size for button text */
padding: 20px; /* Padding inside the buttons */
text-align: center; /* Center-align the text inside buttons */
cursor: pointer; /* Pointer cursor on hover */
transition: background-color 0.3s ease; /* Smooth transition for hover effect */
}
/* Hover effect for buttons */
.btn:hover {
background-color: #ddd; /* Darker gray on hover */
}
/* Active state for buttons (when clicked) */
.btn:active {
background-color: #bbb; /* Even darker on click */
}
/* Styling for operator buttons (addition, subtraction, etc.) */
.btn.operator {
background-color: #f9a825; /* Yellow background for operators */
color: white; /* White text */
}
.btn.operator:hover {
background-color: #f57f17; /* Darker yellow on hover */
}
.btn.operator:active {
background-color: #ff6f00; /* Even darker on click */
}
/* Styling for the 'C' (Clear) and 'Backspace' buttons */
.btn.clear {
background-color: #d32f2f; /* Red background for clear */
color: white; /* White text */
}
.btn.clear:hover {
background-color: #c62828; /* Darker red on hover */
}
.btn.clear:active {
background-color: #b71c1c; /* Even darker red on click */
}
/* Styling for the 'Equals' button */
.btn.equals {
background-color: #388e3c; /* Green background for equals */
color: white; /* White text */
}
.btn.equals:hover {
background-color: #2c6b2f; /* Darker green on hover */
}
.btn.equals:active {
background-color: #1b5e20; /* Even darker green on click */
}
Source: Calculator CSS
Explanation of CSS:
upGrad’s Exclusive Software and Tech Webinar for you –
SAAS Business – What is So Different?
Now, we will add JavaScript to bring the calculator to life. The JavaScript will handle user interactions like clicking buttons, performing calculations, and updating the display based on user input.
// Get the display element and all button elements
const display = document.getElementById('display');
const buttons = document.querySelectorAll('.btn');
// Initialize a variable to store the current calculation input
let currentInput = '';
// Add event listeners for each button
buttons.forEach(button => {
button.addEventListener('click', (e) => {
const value = e.target.textContent; // Get the value of the clicked button
if (value === 'C') {
// If 'C' is clicked, clear the display and reset the input
currentInput = '';
display.value = '';
} else if (value === '←') {
// If '←' is clicked, remove the last character from input
currentInput = currentInput.slice(0, -1);
display.value = currentInput;
} else if (value === '=') {
// If '=' is clicked, evaluate the expression and show the result
try {
currentInput = eval(currentInput).toString(); // Use eval() to evaluate the math expression
display.value = currentInput;
} catch (error) {
// If the expression is invalid, display 'Error'
display.value = 'Error';
currentInput = '';
}
} else {
// For other buttons (numbers and operators), append the value to the current input
currentInput += value;
display.value = currentInput; // Update the display with the current input
}
});
});
Source: Calculator js
Explanation of JavaScript:
If you're interested in learning how to build a calculator in C, we invite you to explore our detailed tutorial. This step-by-step guide will walk you through the process of creating a functional calculator program using C.
We hope that this instructional guide helped to learn how to build a calculator in Javascript. With the successful execution of our steps, You now have a complete and functional calculator using HTML, CSS, and JavaScript. The comments in the code explain each part of the project, and the explanations at the end of each section provide context for what each part of the code does. This should help you or any reader understand how the calculator works and how each technology contributes to the final result.
If you enjoyed building this calculator and are eager to dive deeper into web development, JavaScript, or full-stack programming, UpGrad offers industry-leading courses designed to help you master these skills and advance your career.
Join UpGrad learning today and start building your future as a web developer. Don't wait—your journey to becoming an expert developer begins now! Feel free to test the code by copying and pasting it into an online code editor to see the result in action!
Enhance your expertise with our Software Development Free Courses. Explore the programs below to find your perfect fit.
Elevate your expertise with our range of Popular Software Engineering Courses. Browse the programs below to discover your ideal fit.
Advance your in-demand software development skills with our top programs. Discover the right course for you below.
Explore popular articles related to software to enhance your knowledge. Browse the programs below to find your ideal match.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources