HTML · HTML with CSS · Lesson 23 of 32

HTML with CSS

HTML with CSS

HTML defines the structure and meaning of webpage content, while CSS (Cascading Style Sheets) controls how that content is presented.

HTML can define headings, paragraphs, links, images, forms, tables and sections. CSS can control their colours, fonts, spacing, alignment, dimensions, borders, backgrounds and responsive layout.

Core Principle:

HTML → Structure & Meaning
CSS → Presentation & Layout

1. Why Use CSS with HTML?

Without CSS, a webpage mainly presents its semantic content using the browser's default styles. CSS allows developers to create consistent and visually organized interfaces.

CSS can control:

  • Colours
  • Fonts and typography
  • Text alignment
  • Margins and padding
  • Width and height
  • Borders and shadows
  • Backgrounds
  • Page layouts
  • Responsive behaviour
  • Animations and transitions
Best Practice:

Keep content and semantics in HTML and presentation rules in CSS. This improves maintainability, consistency and reusability.

2. CSS Syntax

A CSS rule generally consists of a selector followed by one or more declarations.

p {
    color: blue;
    font-size: 18px;
}
Part Example Purpose
Selector p Selects the HTML element.
Property color Specifies what aspect is being styled.
Value blue Specifies the property's value.
Declaration color: blue; Property-value combination.

3. Ways to Add CSS to HTML

CSS can be associated with HTML in three common ways:

  1. Inline CSS
  2. Internal CSS
  3. External CSS

4. Inline CSS

Inline CSS is written directly inside the style attribute of an HTML element.

<p style="color: blue;">
    Welcome to Web Development
</p>

Advantages

  • Quick for testing a single element.
  • Easy to demonstrate small examples.

Disadvantages

  • Difficult to maintain across large websites.
  • Styles cannot be easily reused.
  • Mixes presentation with HTML structure.
  • Can make HTML unnecessarily large.
Professional Practice:

Avoid inline CSS for maintainable production websites unless there is a specific reason to use it.

5. Internal CSS

Internal CSS is written inside a <style> element in the <head> section of the HTML document.

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Internal CSS</title>

    <style>

        h1 {
            color: darkblue;
        }

        p {
            font-size: 18px;
        }

    </style>

</head>

<body>

    <h1>Web Development</h1>

    <p>
        Learn HTML and CSS.
    </p>

</body>

</html>

Internal CSS can be useful for a single-page demonstration, but it is generally less reusable than an external stylesheet.

6. External CSS

External CSS is stored in a separate .css file and linked to the HTML document.

HTML

<head>

    <link
        rel="stylesheet"
        href="styles.css">

</head>

styles.css

h1 {
    color: darkblue;
}

p {
    font-size: 18px;
}
Recommended for Websites:

External stylesheets are generally preferred for multi-page websites because the same CSS can be reused across many HTML documents.

7. Inline vs Internal vs External CSS

Feature Inline Internal External
Location HTML element <style> Separate CSS file
Reusability Low Page-level High
Maintainability Low Moderate High
Best suited for Small tests Single-page examples Websites and applications

8. Linking an External Stylesheet

The <link> element is used to associate an external stylesheet with an HTML document.

<link
    rel="stylesheet"
    href="css/styles.css">
Attribute Purpose
rel Describes the relationship between the documents.
stylesheet Indicates that the linked resource is a stylesheet.
href Specifies the location of the CSS file.

9. CSS Selectors

A CSS selector identifies the HTML elements to which a rule should apply.

Element Selector

p {
    color: #333;
}

This selects all <p> elements.

Multiple Element Selectors

h1,
h2,
h3 {
    font-family: Arial, sans-serif;
}

Multiple selectors can share the same declarations.

10. Class Selectors

The class attribute allows HTML elements to be assigned to a reusable styling category.

HTML

<p class="highlight">
    Important information.
</p>

<p class="highlight">
    Another important message.
</p>

CSS

.highlight {
    font-weight: bold;
}

A class selector begins with a dot (.).

11. ID Selectors

An id identifies a particular element within a document.

<section id="about">

    <h2>About the Course</h2>

</section>
#about {
    padding: 20px;
}
Remember:

Class selectors are commonly used for reusable styling, while an ID identifies a particular element.

12. Attribute Selectors

CSS can select elements based on their attributes.

input[type="email"] {
    border: 1px solid #999;
}

This targets input elements whose type attribute is email.

13. Descendant Selectors

A descendant selector targets elements located inside another element.

article p {
    line-height: 1.6;
}

This targets paragraphs that occur inside an article.

14. Child Selector

The > combinator selects direct children.

nav > ul {
    list-style: none;
}

This selects only ul elements that are direct children of nav.

15. Grouping Selectors

Multiple selectors can be grouped using commas.

h1,
h2,
h3 {
    color: #222;
}

This avoids repeating the same declaration block.

16. Common CSS Properties

Property Purpose
color Sets text colour.
background-color Sets background colour.
font-size Controls text size.
font-family Specifies the typeface.
font-weight Controls font weight.
text-align Controls horizontal text alignment.
margin Controls outside spacing.
padding Controls inside spacing.
border Defines an element border.
width Controls width.
height Controls height.

17. Colours in CSS

CSS supports several ways to represent colours.

h1 {
    color: red;
}

p {
    color: #333333;
}

section {
    background-color: rgb(245, 245, 245);
}

Common Colour Formats

  • Named colours
  • Hexadecimal colours
  • RGB
  • RGBA
  • HSL
  • HSLA

18. CSS Box Model

Every HTML element can be considered as a rectangular box. The CSS box model consists of:

  1. Content
  2. Padding
  3. Border
  4. Margin
Component Meaning
Content The actual text, image or other content.
Padding Space between content and border.
Border Boundary surrounding padding and content.
Margin Space outside the border.
.card {
    padding: 20px;
    border: 1px solid #ccc;
    margin: 20px;
}

19. Width, Height and Sizing

CSS provides several ways to specify dimensions.

.container {
    width: 80%;
    max-width: 1200px;
    min-height: 300px;
}

Relative units such as percentages can be useful in responsive layouts, while constraints such as max-width can prevent content from becoming excessively wide.

20. CSS Units

Unit Type Example
px Pixel unit 16px
% Relative to containing context 80%
em Relative to font sizing context 1.2em
rem Relative to root font size 1rem
vw Relative to viewport width 50vw
vh Relative to viewport height 50vh

21. The display Property

The display property determines how an element participates in layout.

.box {
    display: block;
}

.inline-item {
    display: inline;
}

.card {
    display: inline-block;
}

Common Values

  • block
  • inline
  • inline-block
  • flex
  • grid
  • none

22. CSS Flexbox

Flexbox is a CSS layout system designed primarily for arranging elements along one dimension.

.course-list {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
}

HTML provides the elements, while CSS determines how they are arranged.

<div class="course-list">

    <article class="course">
        <h2>HTML</h2>
    </article>

    <article class="course">
        <h2>CSS</h2>
    </article>

    <article class="course">
        <h2>JavaScript</h2>
    </article>

</div>

23. CSS Grid

CSS Grid is a two-dimensional layout system suitable for arranging content across rows and columns.

.courses {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
}
Quick Comparison:

Flexbox is primarily one-dimensional, while Grid is designed for two-dimensional layouts.

24. The Cascade

The word Cascading in CSS refers to the process by which the browser determines which applicable declarations should win when multiple rules affect an element.

p {
    color: blue;
}

.article-text {
    color: green;
}

If a paragraph has the class article-text, the class selector generally has greater specificity than the element selector.

25. CSS Specificity

Specificity is one factor used by CSS to determine which declaration takes precedence when competing rules apply.

Selector Type Example
Element p
Class .note
ID #main
Inline style style="..."
Important:

CSS precedence is not determined by specificity alone. The cascade also considers factors such as origin, importance and source order.

26. CSS Inheritance

Some CSS properties can be inherited from a parent element by its descendants.

body {
    font-family: Arial, sans-serif;
}

p {
    color: #333;
}

Font-related properties such as font-family commonly inherit, whereas many box-model properties such as margin do not.

27. Pseudo-Classes

Pseudo-classes select elements according to a particular state or condition.

a:hover {
    text-decoration: underline;
}

input:focus {
    outline: 2px solid blue;
}

Common examples include :hover, :focus, :active and :checked.

28. Pseudo-Elements

Pseudo-elements allow developers to style a particular part of an element or generate certain content.

p::first-letter {
    font-size: 2rem;
}

.note::before {
    content: "Note: ";
}

29. Responsive CSS with HTML

HTML provides the semantic structure and CSS adapts its presentation to available space.

HTML

<section class="courses">

    <article class="course">
        <h2>HTML</h2>
        <p>Learn HTML fundamentals.</p>
    </article>

    <article class="course">
        <h2>CSS</h2>
        <p>Learn modern CSS.</p>
    </article>

</section>

CSS

.courses {
    display: grid;
    grid-template-columns: 1fr;
    gap: 20px;
}

@media (min-width: 768px) {

    .courses {
        grid-template-columns: repeat(2, 1fr);
    }

}

The same HTML can therefore support different layouts without creating separate pages for different devices.

30. CSS Custom Properties

CSS custom properties, commonly called CSS variables, allow reusable values to be defined and referenced.

:root {
    --primary-color: #1a4d8f;
    --spacing: 16px;
}

.button {
    background-color: var(--primary-color);
    padding: var(--spacing);
}
Advantage:

Reusable values make large stylesheets easier to maintain and support consistent design systems.

31. Browser Default Styles

Browsers apply default styles to many HTML elements. Developers may intentionally reset or normalize selected styles when building a design system.

* {
    box-sizing: border-box;
}

body {
    margin: 0;
}

The exact reset strategy depends on the requirements of the project.

32. HTML + CSS Best Practices

  1. Use semantic HTML for structure.
  2. Prefer external stylesheets for reusable website styling.
  3. Use meaningful class names.
  4. Avoid unnecessary IDs for styling.
  5. Keep presentation rules in CSS.
  6. Avoid excessive specificity.
  7. Use responsive layout techniques.
  8. Maintain keyboard accessibility.
  9. Keep CSS organized and reusable.
  10. Test across browsers and screen sizes.

33. Common Mistakes

Mistake Better Approach
Using inline styles everywhere Use reusable CSS classes and external stylesheets.
Using HTML for visual spacing Use CSS margin and padding.
Using headings only for appearance Use headings according to document hierarchy.
Overusing IDs for styling Prefer reusable classes where appropriate.
Using excessive !important Improve selector organization and specificity.
Fixed-width layouts everywhere Use flexible and responsive layout techniques.
Duplicating CSS unnecessarily Use reusable classes, variables and shared styles.

34. Interview Questions

1. What is CSS?

View Answer

CSS stands for Cascading Style Sheets. It is used to control the presentation, styling and layout of HTML documents.

2. What are the three ways to apply CSS?

View Answer

Inline CSS, internal CSS and external CSS.

3. Which method is generally preferred for large websites?

View Answer

External CSS is generally preferred because styles can be reused across multiple HTML documents and maintained centrally.

4. What is the difference between class and ID?

View Answer

A class represents a reusable category that can be assigned to multiple elements. An ID identifies a particular element within a document.

5. What is the CSS box model?

View Answer

The CSS box model describes an element in terms of content, padding, border and margin.

6. What is the difference between margin and padding?

View Answer

Padding is the space between an element's content and its border. Margin is the space outside the border.

7. What is CSS specificity?

View Answer

Specificity is a mechanism used by the CSS cascade to determine which competing selector has greater precedence.

8. What is the difference between Flexbox and Grid?

View Answer

Flexbox is primarily designed for one-dimensional layouts, whereas CSS Grid is designed for two-dimensional row-and-column layouts.

35. Exam Questions

Q1. Define CSS.

Answer

CSS, or Cascading Style Sheets, is a stylesheet language used to define the presentation and layout of HTML documents.

Q2. Differentiate between inline CSS and external CSS.

Answer

Inline CSS is written directly in an HTML element's style attribute, while external CSS is stored in a separate stylesheet that can be reused across multiple HTML pages.

Q3. What is the purpose of the <link> element when working with CSS?

Answer

It associates an external resource, such as a stylesheet, with the HTML document.

Q4. Explain the CSS box model.

Answer

The CSS box model consists of content, padding, border and margin. Content contains the actual material, padding surrounds the content, border surrounds the padding, and margin creates space outside the border.

Q5. What is the difference between a class selector and an ID selector?

Answer

A class selector begins with a dot and is intended for reusable groups of elements. An ID selector begins with a hash and targets an element identified by a particular ID.

Q6. Why should HTML and CSS be separated?

Answer

Separation keeps structure and presentation distinct, making webpages easier to maintain, reuse, update and scale.

36. Practical Task — Style a Course Page

Create an HTML course page and style it using an external CSS stylesheet.

HTML Requirements

  1. Create a semantic header.
  2. Add navigation links.
  3. Create a main heading.
  4. Add at least two course sections.
  5. Add an image with meaningful alt text.
  6. Add a registration form.
  7. Create a footer.

CSS Requirements

  1. Use an external stylesheet.
  2. Create reusable classes.
  3. Style headings and paragraphs.
  4. Apply spacing using margin and padding.
  5. Use the box model.
  6. Create a responsive layout.
  7. Use Flexbox or Grid.
  8. Add a hover or focus state.

Advanced Challenge

Create a reusable design system using CSS custom properties for colours, spacing and typography.

37. Quick Revision

Concept Remember
HTML Defines structure and meaning.
CSS Controls presentation and layout.
Inline CSS Written in the style attribute.
Internal CSS Written inside a style element.
External CSS Stored in a separate stylesheet.
Class Reusable selector category.
ID Identifies a particular element.
Box Model Content + Padding + Border + Margin.
Flexbox Primarily one-dimensional layout.
Grid Two-dimensional row-and-column layout.
Specificity Helps determine which competing rule wins.
Media Query Applies CSS based on conditions such as viewport size.
Exam Mantra:

HTML → Structure | CSS → Style | Selector → Target | Property → What to Style | Value → How to Style | Class → Reusable | ID → Specific | Box Model → Content + Padding + Border + Margin | Flexbox → 1D | Grid → 2D