Lecture 2

March 12, 2025

What html, css, js are, how they work together

How Files Are Loaded in HTML (CSS, JS)

When you type a URL like “google.com” into your browser, a complex but fascinating process begins:

  1. The browser initiates an HTTP request to the server hosting the website
  2. The server responds by sending back the HTML file
  3. The browser starts parsing this HTML file line by line
  4. When the browser encounters references to other files (CSS, JavaScript, images), it makes additional HTTP requests for each one

The Loading Process in Detail

When your browser receives the HTML file, it begins building what’s called the Document Object Model (DOM) - a tree-like representation of the page’s structure. As it’s building this tree, it looks for special tags like:

<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>
<img src="image.jpg">

Each of these tags tells the browser: “I need another file to complete this page.” The browser then sends additional HTTP requests to retrieve these files.

For example, when encountering a CSS link, the browser:

  1. Pauses rendering if the CSS is render-blocking
  2. Sends an HTTP request to the URL in the href attribute
  3. Waits for the server to respond
  4. Applies the received styles to the DOM

JavaScript loading works in a similar way, but with some important nuances:

  • By default, JavaScript files block rendering until they’re downloaded and executed
  • Modern techniques like defer and async attributes can modify this behavior:
<script src="script.js" defer></script> <!-- Loads after HTML parsing -->
<script src="analytics.js" async></script> <!-- Loads asynchronously -->

This sequence is why you sometimes see a website appear in stages - first the structure, then the styling, and finally the interactive elements.

Real-world Example

Consider this simple HTML file:

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="styles.css">
  <script src="script.js" defer></script>
</head>
<body>
  <h1>Hello World</h1>
  <img src="profile.jpg">
</body>
</html>

The browser would make at least four HTTP requests:

  1. Initial request for the HTML file
  2. Request for styles.css
  3. Request for script.js
  4. Request for profile.jpg

This is why website optimization often focuses on reducing the number and size of these requests.

For further reading, MDN has an excellent article on this process: Resource loading

What HTML, CSS, and JavaScript Are

These three technologies form the foundation of the modern web, each with a distinct purpose.

HTML: The Structure

HTML (HyperText Markup Language) defines the structure and content of a webpage. Think of it as the skeleton of a website.

HTML uses elements enclosed in tags (like <h1>, <p>, <div>) to mark up content and give it meaning. For example:

<article>
  <h1>My First Article</h1>
  <p>This is a paragraph with some <strong>important</strong> text.</p>
  <img src="cat.jpg" alt="A cute cat">
</article>

In this example:

  • <article> indicates this is a self-contained piece of content
  • <h1> defines the main heading
  • <p> marks a paragraph
  • <strong> indicates text that should be emphasized
  • <img> embeds an image with alternative text for accessibility

HTML is declarative - it describes what something is, not how it should look or behave.

MDN Documentation: HTML Basics

CSS: The Appearance

CSS (Cascading Style Sheets) controls how HTML elements look on the page. If HTML is the skeleton, CSS is the skin, clothing, and makeup.

CSS consists of rules that select elements and apply styling properties to them:

h1 {
  color: navy;
  font-size: 32px;
  text-align: center;
}

p {
  line-height: 1.5;
  margin-bottom: 20px;
}

img {
  border-radius: 50%;
  max-width: 100%;
}

This CSS would:

  • Make all <h1> headings navy-colored, larger, and centered
  • Give paragraphs more readable line spacing and bottom margin
  • Make all images circular and responsive

CSS can be incredibly powerful, allowing for complex layouts, animations, and responsive designs that adapt to different screen sizes.

MDN Documentation: CSS Basics

JavaScript: The Behavior

JavaScript adds interactivity and dynamic behavior to web pages. If HTML is the skeleton and CSS is the appearance, JavaScript is the muscles and nervous system that allow movement and reaction.

JavaScript can:

  • Respond to user actions like clicks and keyboard input
  • Modify the DOM (add, remove, or change elements)
  • Fetch new data from servers without reloading the page
  • Create animations and complex interactions

Here’s a simple example:

// When the button is clicked, change the heading text
document.getElementById('changeButton').addEventListener('click', function() {
  document.querySelector('h1').textContent = 'Text Changed!';
  
  // Also add a new paragraph
  const newParagraph = document.createElement('p');
  newParagraph.textContent = 'This paragraph was added by JavaScript!';
  document.body.appendChild(newParagraph);
});

This code waits for a user to click a button, then changes the text of the first heading and adds a new paragraph to the page - all without reloading.

MDN Documentation: JavaScript Basics

How They Work Together

These three technologies have distinct roles that complement each other:

  • HTML provides structure and content (the “what”)
  • CSS provides styling and layout (the “how it looks”)
  • JavaScript provides interactivity and dynamic behavior (the “what it does”)

A well-built website uses each for its intended purpose, creating a separation of concerns that makes development more maintainable.

What Parent, Children, and Siblings Are

The DOM (Document Object Model) that browsers create from HTML has a family-tree-like structure, with elements nested inside others. This gives rise to family relationship terminology:

Parent Elements

A parent element directly contains other elements. For example:

<div>  <!-- Parent -->
  <p>Some text</p>  <!-- Child -->
</div>

Here, the <div> is the parent of the <p> element. Parent elements:

  • Contain and wrap their children
  • Often pass certain CSS properties down to their children
  • Can have multiple children
  • Are responsible for defining the container in which children exist

Child Elements

A child element is contained directly within another element. In the example above, the <p> is a child of the <div>. Child elements:

  • Inherit certain properties from their parents
  • Are positioned relative to their parent by default
  • Can only have one parent

Siblings

Siblings are elements that share the same parent:

<ul>  <!-- Parent -->
  <li>First item</li>  <!-- Sibling 1 -->
  <li>Second item</li>  <!-- Sibling 2 -->
  <li>Third item</li>  <!-- Sibling 3 -->
</ul>

All three <li> elements are siblings because they share the same parent (<ul>). Siblings:

  • Appear sequentially in the DOM
  • Can interact with each other via JavaScript
  • Often have similar styling

Descendants and Ancestors

Beyond immediate family, we also have:

  • Descendants: All elements nested inside an element (children, grandchildren, etc.)
  • Ancestors: All elements that contain an element (parent, grandparent, etc.)
<article>  <!-- Ancestor of everything -->
  <header>  <!-- Parent of h1, Descendant of article -->
    <h1>Title</h1>  <!-- Child of header, Descendant of article -->
  </header>
  <div class="content">  <!-- Sibling of header -->
    <p>First paragraph</p>  <!-- Child of div, Descendant of article -->
    <p>Second paragraph</p>  <!-- Sibling of first p -->
  </div>
</article>

Understanding these relationships is crucial for both CSS selection and JavaScript manipulation:

/* CSS targeting based on relationships */
article p {  /* Selects all paragraphs that are descendants of article */
  color: blue;
}

header > h1 {  /* Selects h1 elements that are direct children of header */
  font-size: 2em;
}

p + p {  /* Selects paragraphs that are immediately preceded by another paragraph (siblings) */
  margin-top: 0.5em;
}
// JavaScript traversal based on relationships
const article = document.querySelector('article');
const paragraphs = article.querySelectorAll('p');  // Find descendant paragraphs
const header = article.firstElementChild;  // Get first child
const sibling = header.nextElementSibling;  // Get header's next sibling

MDN Documentation: Traversing an HTML table with JavaScript and DOM Interfaces

Elements That Can or Cannot Have Children

In HTML, elements fall into two major categories regarding their ability to contain other elements:

Container Elements (Can Have Children)

Most HTML elements can contain other elements or text. These are known as container elements or non-void elements. Examples include:

  • <div>: General-purpose container
  • <p>: Paragraph
  • <ul> and <ol>: Unordered and ordered lists
  • <article>, <section>, <header>, <footer>: Semantic containers
  • <form>: Container for form elements
  • <button>: Can contain text and other elements

Container elements must have an opening and closing tag:

<div>
  <p>This paragraph is a child of the div</p>
  <p>So is this one</p>
</div>

Void Elements (Cannot Have Children)

Some HTML elements cannot contain other elements. These are called void elements or self-closing elements. Examples include:

  • <img>: Image embedding
  • <input>: Form input field
  • <br>: Line break
  • <hr>: Horizontal rule
  • <meta>: Metadata
  • <link>: External resource link
  • <source>: Media source

Void elements have only one tag and are written with a trailing slash in XHTML (though it’s optional in HTML5):

<img src="image.jpg" alt="Description">
<input type="text" name="username">
<br>
<meta charset="UTF-8">

Since these elements cannot have children, attempting to add content inside them will not work as expected:

<!-- This won't work as intended -->
<img src="image.jpg">This text won't be displayed as expected</img>

<!-- Instead, use attributes to provide additional information -->
<img src="image.jpg" alt="Description" title="Tooltip text">

Replaced Elements

Some elements are called replaced elements because their content is replaced by something else. For example, the <img> tag is replaced by the actual image file. Other replaced elements include:

  • <video>
  • <audio>
  • <canvas>
  • <iframe>

While these may look like they contain children, their visual representation is actually generated from external sources or scripts.

Practical Considerations

Understanding which elements can have children affects how you structure your HTML:

  1. Nesting Rules: Some elements have specific rules about what they can contain:

    • <ul> and <ol> should only have <li> children
    • <table> has a specific structure with <thead>, <tbody>, <tr>, <td>, etc.
    • <select> should contain only <option> or <optgroup> elements
  2. Semantic Meaning: Using the right container elements gives your content proper meaning:

    • Text content should go in <p>, <h1>-<h6>, or other text-related elements
    • Related content should be grouped in semantic containers like <article> or <section>
  3. Styling Considerations: Parent-child relationships affect CSS:

    • Layout properties like flexbox and grid only work on the children of elements they’re applied to
    • Some properties cascade down from parents to children

MDN Documentation: HTML elements reference

Additional Important Concepts

The Rendering Process

Understanding how browsers render web pages helps explain why HTML, CSS, and JavaScript load the way they do:

  1. Parsing HTML: The browser parses HTML into the DOM
  2. Processing CSS: It constructs the CSS Object Model (CSSOM)
  3. Combining DOM and CSSOM: These combine to form the Render Tree
  4. Layout: The browser calculates the size and position of each element
  5. Painting: Finally, it draws the pixels to the screen

This process explains why some resources are “render-blocking” - they pause this pipeline until they’re loaded.

For an in-depth exploration, see: Critical Rendering Path

The Box Model

Every HTML element is represented as a rectangular box, with:

  • Content: The actual content area
  • Padding: Space between content and border
  • Border: Line around the padding
  • Margin: Space outside the border

This “box model” is fundamental to understanding CSS layout:

div {
  width: 300px;
  padding: 20px;
  border: 1px solid black;
  margin: 10px;
}

The total width taken by this div would be 300px (content) + 40px (padding left+right) + 2px (border left+right) + 20px (margin left+right) = 362px.

MDN Documentation: The box model

Responsiveness

Modern websites need to work on devices of all sizes. Responsive design techniques include:

  • Media Queries: Apply different CSS based on screen size

    @media (max-width: 600px) {
      .sidebar {
        display: none;
      }
    }
  • Flexible Grids: Using percentage-based widths

    .column {
      width: 33.33%;
    }
  • Flexible Images: Ensuring images don’t overflow their containers

    img {
      max-width: 100%;
      height: auto;
    }

Google has a comprehensive guide: Responsive Web Design Basics

< Look at other lectures