Learn how to create a tax calculator using HTML, CSS, and JavaScript. This simple guide includes steps, code, and tips to make your project fast and efficient.
Table of Contents
Do you want to create a simple and useful tax calculator using HTML, CSS, and JavaScript? This project is perfect for beginners who want to improve their coding skills while building a practical tool. A tax calculator helps users calculate taxes on an amount based on a given tax rate.
In this guide, you will learn how to design a clean user interface with HTML and CSS and add functionality using JavaScript.
Prerequisites
Before starting, make sure you have:
- A basic understanding of HTML, CSS, and JavaScript.
- A code editor like Visual Studio Code.
- A web browser to test your project.
Source Code
Step 1 (HTML Code):
To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our tax calculator.
Here’s a breakdown of its structure and functionality:
1. Document Declaration and HTML Structure
<!doctype html>
<html lang="en">
<!doctype html>
: Declares the document as HTML5.<html lang="en">
: Specifies the language of the document as English.
2. <head>
Section
Contains metadata and links to stylesheets and fonts.
<meta charset="UTF-8" />
<meta charset="UTF-8">
: Specifies the character encoding, ensuring support for special characters.
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport">
: Ensures the page is responsive and adjusts well to different screen sizes.
<title>Tax Calculator</title>
<title>
: Sets the page title displayed on the browser tab.
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet">
- Google Fonts Link: Loads the "Poppins" font for styling the text.
<link rel="stylesheet" href="styles.css">
- Stylesheet Link: Links to an external CSS file (
styles.css
) for styling the page.
3. <body>
Section
Contains the main content of the page.
Container for the Calculator
<div class="container">
- Wraps the entire calculator for styling and layout purposes.
Heading
<h1>Tax Calculator</h1>
- Displays the title of the page.
4. Form for User Input
<form id="taxForm" action="#" method="get">
<form>
: Represents the form for user inputs.id="taxForm"
: Assigns an ID for JavaScript targeting.action="#"
: Indicates no form submission to a server.method="get"
: Specifies the HTTP GET method for form data.
Input Fields
- Calculation Type Dropdown
<select id="calculationType" required>
<select>
: Dropdown to choose between two calculation types:- Calculate Tax of Total Amount
- Calculate Tax Money to Get Total Amount
required
: Ensures the user selects an option.
- Amount Input
<input id="toSpend" type="number" step="0.01" placeholder="Enter amount" required>
<input>
: Field for entering the amount.type="number"
: Accepts only numeric values.step="0.01"
: Allows decimal inputs.placeholder="Enter amount"
: Displays placeholder text.required
: Ensures the field is filled.
- Sales Tax Rate Input
<input id="salesTax" type="number" step="0.01" placeholder="9" required>
- Similar to the amount input, but for entering the sales tax rate.
Buttons
<div class="buttons">
- Calculate Button
<button type="button" id="calculate" class="btn">Calculate</button>
- Triggers JavaScript functionality to calculate the tax and display results.
- Reset Button
<button type="reset" id="reset" class="btn btn-reset">Reset</button>
- Clears all input fields and resets the form.
5. Results Section
<div id="results" class="results hidden">
<div>
: Container for displaying results.id="results"
: Targeted by JavaScript to update results dynamically.class="results hidden"
: Initially hidden using thehidden
class.
Results Display
- Amount Before Tax
<span id="displayAmount">$0.00</span>
- Sales Tax
<span id="displayTax">$0.00</span>
- Total Amount
<span id="totalAmount">$0.00</span>
6. JavaScript Link
<script src="script.js"></script>
- Links an external JavaScript file (
script.js
) to handle calculations and dynamic updates.
Step 2 (CSS Code):
Once the basic HTML structure of the tax calculator is in place, the next step is to add styling to the calculator using CSS.
Here's an explanation of the code:
1. Global Styles
body {
font-family: 'Poppins', sans-serif;
background: #f0f4f8;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
}
font-family
: Sets the primary font to "Poppins" with a fallback tosans-serif
.background
: Applies a light grayish-blue background color.margin
andpadding
: Removes default spacing around the body.display: flex
: Enables a flexbox layout for centering content.justify-content: center
: Horizontally centers content.align-items: center
: Vertically centers content.
2. Container Styling
.container {
background: #ffffff;
margin: 20px 0;
padding: 30px;
border-radius: 10px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
width: 90%;
max-width: 400px;
text-align: center;
}
background
: Sets a white background for the container.margin
: Adds vertical spacing.padding
: Adds inner spacing around content.border-radius
: Rounds the corners of the container.box-shadow
: Adds a subtle shadow for a lifted effect.width
andmax-width
: Ensures the container is responsive and does not exceed 400px.text-align: center
: Centers text within the container.
3. Headings
h1 {
color: #333;
margin-bottom: 20px;
font-size: 1.8rem;
}
color
: Sets a dark gray color for the heading.margin-bottom
: Adds spacing below the heading.font-size
: Sets the font size to 1.8rem for emphasis.
4. Form Styling
form {
margin-bottom: 20px;
}
margin-bottom
: Adds spacing below the form.
Form Groups
.form-group {
margin-bottom: 15px;
}
margin-bottom
: Adds spacing between form elements.
5. Input and Select Fields
select, input {
font-family: 'Poppins', sans-serif;
width: 100%;
padding: 10px;
font-size: 1rem;
border: 1px solid #ddd;
border-radius: 5px;
}
font-family
: Ensures consistent typography.width
: Makes the fields stretch to full width.padding
: Adds inner spacing for better usability.font-size
: Sets a readable font size.border
: Adds a light gray border.border-radius
: Rounds the edges.
Focus Styles
select:focus, input:focus {
border-color: #825cff;
outline: none;
box-shadow: 0 0 5px rgba(130, 92, 255, 0.3);
}
border-color
: Changes the border color to purple on focus.outline: none
: Removes the default outline.box-shadow
: Adds a subtle glow effect.
6. Buttons
.buttons {
display: flex;
justify-content: space-between;
}
display: flex
: Aligns buttons horizontally.justify-content: space-between
: Distributes buttons evenly.
Button Styling
.btn {
font-family: 'Poppins', sans-serif;
padding: 10px 20px;
font-size: 1rem;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
padding
: Adds inner spacing for a clickable area.border
: Removes default border.border-radius
: Rounds the edges.cursor: pointer
: Changes the cursor to a pointer on hover.transition
: Smoothly animates background color changes.
Hover Effect
.btn:hover {
opacity: 0.9;
}
- Reduces opacity slightly on hover for a visual cue.
Specific Button Colors
.btn-reset {
background: #f44336;
color: white;
}
.btn {
background: #825cff;
color: white;
}
- Reset Button: Red background.
- Calculate Button: Purple background.
7. Results Section
.results {
background: #f8f9fa;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
- Styled to visually separate results from the form.
Hidden State
.results.hidden {
display: none;
}
- Hides the results section initially.
8. Typography
p {
margin: 10px 0;
font-size: 1rem;
color: #333;
}
small {
color: #888;
}
- Paragraphs: Adds spacing and sets a dark gray color.
- Small Text: Uses a lighter gray for less emphasis.
9. Media Query
@media (max-width: 768px) {
.container {
width: 100%;
padding: 20px;
}
h1 {
font-size: 1.5rem;
}
.btn {
width: 48%;
}
}
- Activates for screens smaller than 768px.
- Container: Adjusts width and padding for smaller screens.
- Heading: Reduces font size.
- Buttons: Makes buttons occupy less width.
body {
font-family: 'Poppins', sans-serif;
background: #f0f4f8;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
}
.container {
background: #ffffff;
margin: 20px 0;
padding: 30px;
border-radius: 10px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
width: 90%;
max-width: 400px;
text-align: center;
}
h1 {
color: #333;
margin-bottom: 20px;
font-size: 1.8rem;
}
form {
margin-bottom: 20px;
}
.form-group {
margin-bottom: 15px;
}
select {
font-family: 'Poppins', sans-serif;
width: 100%;
padding: 10px;
font-size: 1rem;
border: 1px solid #ddd;
border-radius: 5px;
background: #ffffff;
color: #333;
}
select:focus {
border-color: #825cff;
outline: none;
box-shadow: 0 0 5px rgba(130, 92, 255, 0.3);
}
label {
display: block;
font-size: 1rem;
margin-bottom: 8px;
color: #555;
}
input {
font-family: 'Poppins', sans-serif;
width: 100%;
padding: 10px;
font-size: 1rem;
border: 1px solid #ddd;
border-radius: 5px;
}
input:focus {
border-color: #825cff;
outline: none;
box-shadow: 0 0 5px rgba(130, 92, 255, 0.3);
}
.buttons {
display: flex;
justify-content: space-between;
}
.btn {
font-family: 'Poppins', sans-serif;
padding: 10px 20px;
font-size: 1rem;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.btn:hover {
opacity: 0.9;
}
.btn-reset {
background: #f44336;
color: white;
}
.btn {
background: #825cff;
color: white;
}
.results {
background: #f8f9fa;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.results.hidden {
display: none;
}
p {
margin: 10px 0;
font-size: 1rem;
color: #333;
}
small {
color: #888;
}
@media (max-width: 768px) {
.container {
width: 100%;
padding: 20px;
}
h1 {
font-size: 1.5rem;
}
.btn {
width: 48%;
}
}
Step 3 (JavaScript Code):
Finally, we need to create a function in JavaScript.
The JavaScript code is designed to calculate and display tax-related values (like the tax amount, total amount, and pre-tax amount) based on user inputs and their selected calculation type. Here's a detailed explanation:
Key Components
- HTML Elements Selection
calculationType
: Dropdown for selecting the type of calculation (calculateTax
orcalculateInitial
).toSpend
: Input field for the amount to calculate.salesTax
: Input field for the sales tax percentage.calculate
: Button to trigger the calculation.reset
: Button to reset the form.results
: Section to display the results.displayAmount
,displayTax
,totalAmount
: Elements to show calculated values.
Event Listeners
DOMContentLoaded
- Ensures the script runs only after the DOM is fully loaded.
calculate
Button Click- Reads Inputs:
toSpend
: Amount entered by the user.salesTax
: Tax rate entered by the user.
- Validates Inputs:
- Checks if both
toSpend
andsalesTax
are positive numbers. If not, an alert is shown, and the function exits.
- Checks if both
- Calculates Values:
- When
calculationType
iscalculateTax
:tax
=amount * taxRate
total
=amount + tax
beforeTax
=amount
- When
calculationType
iscalculateInitial
:total
=amount
beforeTax
=total / (1 + taxRate)
tax
=total - beforeTax
- When
- Displays Results:
- Updates
displayAmount
,displayTax
, andtotalAmount
with calculated values. - Removes the
hidden
class fromresults
to make it visible.
- Updates
- Reads Inputs:
reset
Button Click- Resets the Form:
- Clears all input fields and sets
calculationType
to its default value. - Hides the
results
section by adding thehidden
class.
- Clears all input fields and sets
- Resets the Form:
Calculation Logic
calculateTax
Mode:- Computes the tax and total amount for a given base amount.
- Example:
amount = 100
,taxRate = 10%
tax = 100 * 0.1 = 10
total = 100 + 10 = 110
calculateInitial
Mode:- Determines the pre-tax amount and tax for a given total amount.
- Example:
total = 110
,taxRate = 10%
beforeTax = 110 / (1 + 0.1) = 100
tax = 110 - 100 = 10
document.addEventListener("DOMContentLoaded", () => {
const calculationType = document.getElementById("calculationType");
const toSpend = document.getElementById("toSpend");
const salesTax = document.getElementById("salesTax");
const calculate = document.getElementById("calculate");
const reset = document.getElementById("reset");
const results = document.getElementById("results");
const displayAmount = document.getElementById("displayAmount");
const displayTax = document.getElementById("displayTax");
const totalAmount = document.getElementById("totalAmount");
calculate.addEventListener("click", () => {
const amount = parseFloat(toSpend.value);
const taxRate = parseFloat(salesTax.value) / 100;
if (isNaN(amount) || amount <= 0 || isNaN(taxRate) || taxRate <= 0) {
alert("Please enter valid positive numbers for both fields.");
return;
}
let beforeTax, tax, total;
if (calculationType.value === "calculateTax") {
tax = amount * taxRate;
total = amount + tax;
beforeTax = amount;
} else if (calculationType.value === "calculateInitial") {
total = amount;
beforeTax = total / (1 + taxRate);
tax = total - beforeTax;
}
displayAmount.textContent = `$${beforeTax.toFixed(2)}`;
displayTax.textContent = `$${tax.toFixed(2)}`;
totalAmount.textContent = `$${total.toFixed(2)}`;
results.classList.remove("hidden");
});
reset.addEventListener("click", () => {
results.classList.add("hidden");
toSpend.value = "";
salesTax.value = "";
calculationType.value = "calculateTax";
});
});
Final Output:
Conclusion:
Building a tax calculator with HTML, CSS, and JavaScript is a great way to improve your web development skills. This project shows how to create a simple tool with an easy-to-use design and working logic. You can make it even better by adding features like advanced tax calculations or better error handling. Keep experimenting to make your tax calculator more useful and fun to use!
That’s a wrap!
I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.
Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee
And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!
Thanks!
Faraz 😊