Coding

HTML, CSS and JavaScript: How They Work Together

HTML, CSS and JavaScript are three separate languages that each do one job on a web page: HTML defines the content and its structure, CSS controls how that content looks, and JavaScript changes the page while someone is using it. A browser reads all three, and they connect through element names, class names and the DOM.

The rest of this page shows the connection with one small page you can save and open, then explains how each file is loaded and what goes wrong most often.

What each language does

MDN describes the three as layers that build on top of one another. In its words, HTML is "the markup language that we use to structure and give meaning to our web content", CSS is "a language of style rules that we use to apply styling to our HTML content", and JavaScript is "a scripting language that enables you to create dynamically updating content".

LanguageJobExample of what it controls
HTMLStructure and meaningHeadings, paragraphs, buttons, images, tables
CSSPresentationColors, fonts, spacing, columns
JavaScriptBehaviorReacting to clicks, updating text, fetching data

Each layer can exist without the next one. A page with only HTML is still readable. Add CSS and it looks designed. Add JavaScript and it can respond. Going the other way does not work: CSS and JavaScript both need HTML elements to point at.

One page that uses all three

This example is a button that shows or hides a message. Create a folder with three files. First, index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Three languages, one page</title>
  <link rel="stylesheet" href="style.css">
  <script defer src="script.js"></script>
</head>
<body>
  <h1>Hello</h1>
  <button id="toggle">Show message</button>
  <p id="message" class="hidden">This text was always in the HTML.</p>
</body>
</html>

Second, style.css:

body {
  font-family: sans-serif;
  margin: 2rem;
}

#message {
  color: #1a5fb4;
  font-size: 1.25rem;
}

.hidden {
  display: none;
}

Third, script.js:

const button = document.querySelector("#toggle");
const message = document.querySelector("#message");

button.addEventListener("click", () => {
  message.classList.toggle("hidden");
});

Open index.html in a browser. You see a heading and a button, and the paragraph is not visible. Click the button and the paragraph appears. Click again and it disappears.

How the three files connect

The files never call each other directly. The HTML is the shared meeting point, and each language finds its target through something written in the HTML.

  • HTML to CSS: the <link rel="stylesheet" href="style.css"> tag loads the stylesheet. The rule #message matches the element with id="message", and .hidden matches any element whose class attribute contains hidden. The paragraph is invisible because of that class, not because the HTML is missing.
  • HTML to JavaScript: the <script> element loads script.js. The call document.querySelector("#toggle") looks up the button by its id and returns that element as an object.
  • JavaScript to CSS: the script does not set colors or visibility itself. It only adds or removes a class name, and the stylesheet decides what that class means.

That last point is the pattern worth copying. According to MDN, classList "contains a live DOMTokenList collection representing the class attribute of the element", and you change it with add(), remove(), replace() and toggle(). toggle() adds the class if it is absent and removes it if it is present. Keeping the visual rules in CSS and the logic in JavaScript means you can restyle the page without touching the script, and rewrite the script without touching the styles.

What the browser does with them

The browser parses the HTML into a tree of objects called the DOM (Document Object Model). CSS rules are matched against those objects to decide how each one is drawn. JavaScript gets access to the same objects through the global document, so when the script changes a class name, the browser re-matches the CSS rules and redraws the element. Nothing reloads, and no HTML file is rewritten on disk. Only the in-memory tree changes.

This is also why a script cannot find an element that has not been parsed yet. That leads to the most common load-order mistake.

Where to put the script tag

MDN's page on the <script> element says that a classic script with no async, defer or type="module" attribute is "fetched and executed immediately before the browser continues to parse the page". If that script sits in the <head> and looks for a button that appears later in the body, querySelector returns null and the next line fails with an error such as TypeError: Cannot read properties of null (reading 'addEventListener').

There are three ordinary fixes:

  • defer: used in the example above. MDN says a deferred script is "meant to be executed after the document has been parsed, but before firing DOMContentLoaded event", and deferred scripts run in the order they appear. It only works on scripts with a src attribute; on inline scripts it has no effect.
  • type="module": MDN's introduction to JavaScript notes that the browser waits for the HTML to be processed before it runs module scripts, and says placing external scripts in the head is usually better than the bottom of the body because the browser can start fetching sooner. One catch from the same page: module scripts opened from a file:// address fail with a cross-origin error, so use a local test server or fall back to defer.
  • Script at the end of <body>: by that point every element above it has been parsed. This is the oldest approach and still works.

async is different from defer. MDN says an async classic script is "fetched in parallel to parsing and evaluated as soon as it is available", with no guaranteed execution order. It suits independent scripts, such as an analytics snippet, and is a poor fit for code that needs the page to be ready.

Inline versus separate files

Both CSS and JavaScript can be written directly in the HTML, with <style> and <script> elements. That is convenient for a single-file demo. For anything with more than one page, separate files are easier to maintain, because one stylesheet and one script can be shared and the HTML stays focused on content. Keep in mind that defer and async only apply to scripts loaded with src.

Check your understanding by changing it

Three small edits show the separation clearly:

  1. Change #1a5fb4 in style.css to another color and reload. The script is untouched, and the message color changes.
  2. Rename the class hidden to concealed in the HTML, the CSS and the script. If you miss one place, the message either never hides or never toggles, which shows how the three files depend on shared names.
  3. Delete the defer attribute and reload. The script now runs while the head is being parsed, the button does not exist yet, and the browser console shows the TypeError above.

When you are ready to learn the language side in more detail, JavaScript for Beginners: The Core Concepts in One Page covers variables, functions, arrays and events.

If the page does not behave

Open the browser's developer tools (F12 in most browsers) and check two places. The Console tab shows JavaScript errors with the file name and line number. The Elements tab shows the live DOM and which CSS rules apply to the selected element, so you can see whether a class was actually added. If a stylesheet or script fails to load, the Network tab lists the request with a 404 status, which usually means the href or src path does not match the file name or folder.

Frequently asked questions

Do I need to learn HTML, CSS and JavaScript in that order?
Yes, that order is the practical one. HTML gives you something to look at, CSS changes how it looks, and JavaScript needs existing elements to change. You can write JavaScript without CSS, but a page with no HTML has nothing for a script to act on.
Can a web page work without JavaScript?
Yes. A page made of HTML alone is a valid web page, and CSS can add layout, colors and some visual effects without any script. JavaScript is needed when the page must react to input, fetch data or change content after it has loaded.
Is JavaScript the same as Java?
No. They are separate languages with different syntax and different uses. JavaScript is the scripting language that runs in web browsers. Java is a different language that is usually compiled and run on a Java virtual machine.
Should I put CSS and JavaScript in the HTML file or in separate files?
Separate files are the usual choice once a project has more than one page, because the browser can reuse one stylesheet and one script across pages and your HTML stays readable. For a single small demo, putting everything in one file is fine.

Sources