CodeNewbie Community ๐ŸŒฑ

Pranab Bhandari
Pranab Bhandari

Posted on

How to Build a CM to Inches Converter with HTML and JavaScript

Converting between cm to Inches is a common task, especially in international contexts where metric and imperial systems meet. In this article, we'll walk through how to build a simple and interactive CM to Inches conversion tool using HTML, CSS, and JavaScript. This is a great beginner project to learn web development fundamentals.

Before we dive into the code, letโ€™s review the conversion formula:

1 inch = 2.54 cm

To convert from cm to inches, divide the centimeter value by 2.54:

inches = cm / 2.54

Step 1: HTML Structure
Start by creating a simple HTML form to input the cm value and show the result.

<!DOCTYPE html>



CM to Inches Converter

CM to Inches Converter


Convert

Step 2: Adding Basic CSS
Letโ€™s add some styling to make the tool user-friendly and visually appealing.

body { font-family: Arial, sans-serif; padding: 20px; max-width: 400px; margin: auto; background-color: #f9f9f9; } input, button { width: 100%; padding: 10px; margin-top: 10px; font-size: 16px; } #result { margin-top: 15px; font-weight: bold; }

Step 3: JavaScript for Conversion
Hereโ€™s the JavaScript function that performs the conversion and displays the result.

function convertToInches() { const cm = document.getElementById("cmInput").value; if (cm === "" || isNaN(cm)) { document.getElementById("result").innerText = "Please enter a valid number."; return; } const inches = (cm / 2.54).toFixed(2); document.getElementById("result").innerText = `${cm} cm = ${inches} inches`; }

Final Code
<!DOCTYPE html>



CM to Inches Converter body { font-family: Arial, sans-serif; padding: 20px; max-width: 400px; margin: auto; background-color: #f9f9f9; } input, button { width: 100%; padding: 10px; margin-top: 10px; font-size: 16px; } #result { margin-top: 15px; font-weight: bold; }

CM to Inches Converter


Convert

function convertToInches() { const cm = document.getElementById("cmInput").value; if (cm === "" || isNaN(cm)) { document.getElementById("result").innerText = "Please enter a valid number."; return; } const inches = (cm / 2.54).toFixed(2); document.getElementById("result").innerText = `${cm} cm = ${inches} inches`; }

Top comments (0)