Build a Simple Kilograms to Grams Converter with HTML, CSS, and JavaScript

javascript dev.to

If you want to practice JavaScript with a tiny but useful project, a weight converter is a good place to start.

In this example, we will build a simple kilograms to grams converter using basic HTML, CSS, and JavaScript.

The logic is straightforward:

1 kilogram = 1000 grams
So the formula is:
grams = kilograms × 1000

Step 1: Create the HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Kilograms to Grams Converter</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 500px;
      margin: 40px auto;
      padding: 20px;
    }

    .converter {
      padding: 20px;
      border: 1px solid #ddd;
      border-radius: 8px;
    }

    input, button {
      width: 100%;
      padding: 10px;
      margin-top: 10px;
      font-size: 16px;
    }

    .result {
      margin-top: 15px;
      font-weight: bold;
    }
  </style>
</head>
<body>
  <div class="converter">
    <h2>Kilograms to Grams Converter</h2>
    <input type="number" id="kgInput" placeholder="Enter kilograms" />
    <button onclick="convertKgToGrams()">Convert</button>
    <div class="result" id="result"></div>
  </div>

  <script>
    function convertKgToGrams() {
      const kg = parseFloat(document.getElementById("kgInput").value);
      const result = document.getElementById("result");

      if (isNaN(kg)) {
        result.textContent = "Please enter a valid number.";
        return;
      }

      const grams = kg * 1000;
      result.textContent = `${kg} kg = ${grams} grams`;
    }
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 2: Understand the JavaScript

The conversion part is only one line:

const grams = kg * 1000;

That works because every kilogram contains exactly 1000 grams.

Example conversions
1 kg = 1000 g
0.5 kg = 500 g
1.5 kg = 1500 g
2.25 kg = 2250 g
Why this is a good beginner project

This small project helps you practice:

taking user input
validating values
handling button clicks
updating the DOM
applying a real-world formula

It is simple, but it teaches the core structure of many JavaScript tools and calculators.

Optional improvement ideas

You can extend this project by adding:

reverse conversion from grams to kilograms
auto-convert while typing
a dropdown for multiple weight units
better styling for mobile devices
Live tool reference

If you want to compare your output with a ready-made tool, you can check this kilograms to grams converter:

kilograms-to-grams

Source: dev.to

arrow_back Back to Tutorials