Okay, let's create a really cool looking calculator, all in a single HTML file with embedded CSS and JavaScript.
We'll go for a sleek, dark-mode, slightly futuristic design with smooth transitions and good usability.
Features:
- Sleek Design: Dark theme, gradients, rounded corners, subtle shadows.
- Responsive: Adapts reasonably well to different screen sizes.
- Full Functionality: Basic arithmetic, percentage, clear, delete, decimal.
- History Display: Shows the previous operation.
- Keyboard Support: Use your keyboard for numbers, operators, Enter, Backspace, Esc.
- Single File: All HTML, CSS, and JS in one
index.html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cool Calculator</title>
<link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&family=Roboto+Mono:wght@400;700&display=swap" rel="stylesheet">
<style>
/* Global Styles & Variables */
:root {
--bg-color: #0d1117;
--calc-bg: #161b22;
--display-bg: #010409;
--text-color-primary: #e6edf3;
--text-color-secondary: #8b949e;
--btn-num-bg: #21262d;
--btn-num-hover: #30363d;
--btn-operator-bg-start: #347d39; /* Green */
--btn-operator-bg-end: #2d8c36;
--btn-operator-hover-start: #3fb950;
--btn-operator-hover-end: #36a646;
--btn-clear-bg: #da3633; /* Red */
--btn-clear-hover: #f85149;
--btn-equals-bg-start: #58a6ff; /* Blue */
--btn-equals-bg-end: #408ecf;
--btn-equals-hover-start: #79c0ff;
--btn-equals-hover-end: #619bdc;
--border-radius: 15px;
--button-radius: 10px;
--shadow-light: rgba(0, 0, 0, 0.4);
--shadow-dark: rgba(0, 0, 0, 0.7);
--focus-glow: 0 0 15px rgba(88, 166, 255, 0.5);
--transition-speed: 0.2s ease;
}
/* Base Styling */
*, *::before, *::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Roboto Mono', monospace; /* Modern monospace for display */
background-color: var(--bg-color);
color: var(--text-color-primary);
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
overflow: hidden; /* Prevent scrollbar from glow effects */
background-image: radial-gradient(circle at top left, var(--calc-bg) 1%, transparent 60%),
radial-gradient(circle at bottom right, var(--btn-num-bg) 1%, transparent 60%);
background-size: 80% 80%;
background-repeat: no-repeat;
background-position: top left, bottom right;
}
/* Calculator Container */
.calculator {
background-color: var(--calc-bg);
border-radius: var(--border-radius);
box-shadow: 0 10px 30px var(--shadow-dark), 0 0 0 1px var(--btn-num-bg);
padding: 20px;
width: 320px; /* Fixed width for classic calculator feel */
min-width: 300px;
max-width: 90vw; /* Responsive on smaller screens */
display: flex;
flex-direction: column;
gap: 15px;
position: relative; /* For the subtle glow */
}
/* Display Area */
.display {
background-color: var(--display-bg);
border-radius: var(--button-radius);
padding: 15px 20px;
text-align: right;
box-shadow: inset 0 2px 5px var(--shadow-dark), 0 0 0 1px var(--btn-num-bg);
min-height: 90px;
display: flex;
flex-direction: column;
justify-content: space-around;
overflow: hidden;
word-wrap: break-word; /* Allow long numbers to wrap */
user-select: text; /* Allow copying result */
cursor: text;
}
.history {
color: var(--text-color-secondary);
font-size: 0.9em;
min-height: 1.2em; /* Ensure consistent height */
white-space: nowrap;
overflow-x: auto;
scrollbar-width: none; /* Hide scrollbar for Firefox */
-ms-overflow-style: none; /* Hide scrollbar for IE/Edge */
}
.history::-webkit-scrollbar { /* Hide scrollbar for Chrome/Safari */
display: none;
}
.current-input {
color: var(--text-color-primary);
font-size: 2.2em;
font-weight: bold;
font-family: 'Orbitron', sans-serif; /* Futuristic font for current input */
white-space: nowrap;
overflow-x: auto;
scrollbar-width: none; /* Hide scrollbar for Firefox */
-ms-overflow-style: none; /* Hide scrollbar for IE/Edge */
}
.current-input::-webkit-scrollbar { /* Hide scrollbar for Chrome/Safari */
display: none;
}
/* Buttons Grid */
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12px;
}
/* Individual Button Styling */
.btn {
background-color: var(--btn-num-bg);
color: var(--text-color-primary);
border: none;
border-radius: var(--button-radius);
padding: 18px;
font-size: 1.5em;
cursor: pointer;
transition: background-color var(--transition-speed), transform var(--transition-speed), box-shadow var(--transition-speed);
box-shadow: 0 4px 8px var(--shadow-light);
-webkit-tap-highlight-color: transparent; /* Remove tap highlight on mobile */
}
.btn:hover:not(:disabled) {
background-color: var(--btn-num-hover);
transform: translateY(-2px);
box-shadow: 0 6px 12px var(--shadow-dark);
}
.btn:active:not(:disabled) {
transform: translateY(0);
box-shadow: 0 2px 4px var(--shadow-light);
filter: brightness(0.9);
}
/* Specific Button Colors */
.btn.operator {
background-image: linear-gradient(135deg, var(--btn-operator-bg-start), var(--btn-operator-bg-end));
color: white;
font-weight: bold;
}
.btn.operator:hover:not(:disabled) {
background-image: linear-gradient(135deg, var(--btn-operator-hover-start), var(--btn-operator-hover-end));
}
.btn.clear-btn {
background-color: var(--btn-clear-bg);
color: white;
font-weight: bold;
}
.btn.clear-btn:hover:not(:disabled) {
background-color: var(--btn-clear-hover);
}
.btn.equals-btn {
background-image: linear-gradient(135deg, var(--btn-equals-bg-start), var(--btn-equals-bg-end));
color: white;
font-size: 2em; /* Larger for impact */
font-weight: bold;
grid-column: span 2; /* Make equals button span two columns */
}
.btn.equals-btn:hover:not(:disabled) {
background-image: linear-gradient(135deg, var(--btn-equals-hover-start), var(--btn-equals-hover-end));
}
.btn[data-value="0"] {
grid-column: span 2; /* Make zero button span two columns */
}
/* Disabled button state */
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
transform: none;
box-shadow: none;
}
/* Keyboard Focus Outline - make it cool too! */
.btn:focus-visible {
outline: none;
box-shadow: var(--focus-glow), 0 4px 8px var(--shadow-light);
}
/* Responsive adjustments */
@media (max-width: 400px) {
.calculator {
padding: 15px;
gap: 10px;
}
.btn {
font-size: 1.3em;
padding: 15px;
}
.current-input {
font-size: 2em;
}
}
</style>
</head>
<body>
<div class="calculator">
<div class="display">
<div class="history"></div>
<div class="current-input">0</div>
</div>
<div class="buttons">
<button class="btn clear-btn" data-action="clear">AC</button>
<button class="btn clear-btn" data-action="delete">DEL</button>
<button class="btn operator" data-value="%">%</button>
<button class="btn operator" data-value="/">/</button>
<button class="btn" data-value="7">7</button>
<button class="btn" data-value="8">8</button>
<button class="btn" data-value="9">9</button>
<button class="btn operator" data-value="*">*</button>
<button class="btn" data-value="4">4</button>
<button class="btn" data-value="5">5</button>
<button class="btn" data-value="6">6</button>
<button class="btn operator" data-value="-">-</button>
<button class="btn" data-value="1">1</button>
<button class="btn" data-value="2">2</button>
<button class="btn" data-value="3">3</button>
<button class="btn operator" data-value="+">+</button>
<button class="btn" data-value="0">0</button>
<button class="btn" data-value=".">.</button>
<button class="btn equals-btn" data-action="equals">=</button>
</div>
</div>
<script>
// DOM Elements
const historyDisplay = document.querySelector('.history');
const currentInputDisplay = document.querySelector('.current-input');
const buttons = document.querySelectorAll('.btn');
// Calculator State Variables
let currentInput = '0';
let historyInput = '';
let operator = null;
let previousValue = null;
let shouldResetDisplay = false; // Flag to clear display after operator or equals
// --- Core Calculator Logic Functions ---
/**
* Updates the text content of the display elements.
*/
function updateDisplay() {
currentInputDisplay.textContent = currentInput;
historyDisplay.textContent = historyInput;
}
/**
* Appends a number or decimal point to the current input.
* @param {string} number - The digit or decimal point to append.
*/
function appendNumber(number) {
if (shouldResetDisplay) {
currentInput = number;
shouldResetDisplay = false;
} else {
if (number === '.' && currentInput.includes('.')) return; // Prevent multiple decimals
if (currentInput === '0' && number !== '.') {
currentInput = number; // Replace initial '0' with new number
} else {
currentInput += number;
}
}
updateDisplay();
}
/**
* Handles the selection of an operator (+, -, *, /, %).
* @param {string} nextOperator - The operator symbol.
*/
function chooseOperator(nextOperator) {
if (currentInput === '') return; // No input to operate on
if (previousValue !== null && operator !== null && !shouldResetDisplay) {
// If there's a pending operation and we press another operator, calculate first
calculate();
}
previousValue = parseFloat(currentInput);
operator = nextOperator;
historyInput = `${currentInput} ${operator}`;
currentInput = '0'; // Clear current input visually for next number
shouldResetDisplay = true; // Next number pressed will clear current display
updateDisplay();
}
/**
* Performs the calculation based on the current state.
*/
function calculate() {
if (operator === null || previousValue === null || currentInput === '') {
return; // Nothing to calculate
}
const current = parseFloat(currentInput);
let result;
switch (operator) {
case '+':
result = previousValue + current;
break;
case '-':
result = previousValue - current;
break;
case '*':
result = previousValue * current;
break;
case '/':
if (current === 0) {
currentInput = 'Error: Div by 0';
historyInput = '';
operator = null;
previousValue = null;
shouldResetDisplay = true;
updateDisplay();
return;
}
result = previousValue / current;
break;
case '%':
// This handles A % B, often interpreted as A * (B/100) or (A/100)
// For a simple calculator, % is often applied to the current input like x / 100
// If we're doing A % B, it's typically a percentage of previousValue
// Let's implement it as: if an operator exists, it's `previousValue * (current/100)`,
// otherwise it's `currentInput / 100` (if called directly on currentInput).
// The button handling should call this with appropriate context.
// Here, we assume '%' as an operator means `previousValue * (current/100)`
result = previousValue * (current / 100);
break;
default:
return;
}
currentInput = roundResult(result).toString();
historyInput = `${previousValue} ${operator} ${current} =`;
operator = null; // Clear operator after calculation
previousValue = null; // Clear previous value
shouldResetDisplay = true; // Next number will start a new calculation
updateDisplay();
}
/**
* Rounds results to avoid floating point inaccuracies, and formats large numbers.
* @param {number} num - The number to round.
* @returns {number|string} The rounded number or formatted string.
*/
function roundResult(num) {
if (Math.abs(num) > 99999999999) { // If number is too long, use scientific notation or limit decimals
return num.toExponential(5);
}
// Limit to a reasonable number of decimal places to prevent common float issues
return parseFloat(num.toFixed(10));
}
/**
* Clears all calculator state.
*/
function clearAll() {
currentInput = '0';
historyInput = '';
operator = null;
previousValue = null;
shouldResetDisplay = false;
updateDisplay();
}
/**
* Deletes the last character from the current input.
*/
function deleteLast() {
if (shouldResetDisplay) { // If display needs reset, delete effectively clears for new input
currentInput = '0';
shouldResetDisplay = false;
} else if (currentInput.length > 1) {
currentInput = currentInput.slice(0, -1);
} else {
currentInput = '0';
}
updateDisplay();
}
/**
* Applies the percentage logic (divides current input by 100).
*/
function applyPercentage() {
if (currentInput === '' || isNaN(parseFloat(currentInput))) return;
let val = parseFloat(currentInput);
if (operator !== null && previousValue !== null) {
// If an operator is active, % acts as "percentage of previous value"
val = previousValue * (val / 100);
historyInput = `${previousValue} ${operator} ${currentInput}%`;
} else {
// Otherwise, it's just value / 100
val = val / 100;
historyInput = `${currentInput}%`;
}
currentInput = roundResult(val).toString();
updateDisplay();
shouldResetDisplay = true; // Prepare for new input
}
// --- Event Handlers ---
/**
* Handles clicks on calculator buttons.
* @param {Event} e - The click event object.
*/
function handleButtonClick(e) {
const button = e.target.closest('.btn'); // Use closest to handle clicks on child elements
if (!button) return;
const value = button.dataset.value;
const action = button.dataset.action;
if (action) {
switch (action) {
case 'clear':
clearAll();
break;
case 'delete':
deleteLast();
break;
case 'equals':
calculate();
break;
}
} else if (value) {
if (['+', '-', '*', '/'].includes(value)) {
chooseOperator(value);
} else if (value === '%') {
applyPercentage();
} else { // It's a number or decimal
appendNumber(value);
}
}
}
/**
* Handles keyboard input.
* @param {KeyboardEvent} e - The keyboard event object.
*/
function handleKeyboard(e) {
const key = e.key;
if (!isNaN(key) || key === '.') { // Numbers and decimal
appendNumber(key);
} else if (['+', '-', '*', '/'].includes(key)) { // Operators
chooseOperator(key);
} else if (key === 'Enter') { // Equals
calculate();
} else if (key === 'Backspace') { // Delete
deleteLast();
} else if (key === 'Escape') { // Clear all
clearAll();
} else if (key === '%') { // Percentage
applyPercentage();
}
// Prevent default browser actions for some keys like space
if (e.key === ' ' || e.key === 'Enter' || e.key === 'Backspace') {
e.preventDefault();
}
}
// --- Initialize ---
buttons.forEach(button => {
button.addEventListener('click', handleButtonClick);
});
document.addEventListener('keydown', handleKeyboard);
// Initial display update
updateDisplay();
</script>
</body>
</html>