Mastering HTML and CSS: A Comprehensive Guide to Modern Web Development 90 HTML and CSS coding examples

Mastering HTML and CSS goes beyond just creating basic layouts in today’s web development landscape. It involves understanding complex design techniques, integrating accessibility features, optimizing for performance, and implementing advanced styling and animations. This ebook addresses these challenges with detailed explanations, hands-on examples, and best practices for coding modern websites.

What You’ll Learn

Whether you’re new to web development or seeking to deepen your skills, this ebook covers essential topics, including:

  • Accessible HTML with ARIA: Make your web pages inclusive by learning how to add ARIA (Accessible Rich Internet Applications) attributes, ensuring that content is accessible to users with disabilities.
  • Background Images, Colors, and Gradients: Master the use of backgrounds with CSS, from simple color fills to complex gradient overlays that add depth and vibrancy.
  • Basic and Advanced HTML Document Structure: Understand the elements that form the backbone of a well-structured HTML document, essential for both SEO and accessibility.
  • Building Interactive Components: Explore how to create modals, navigation bars, tooltips, and responsive image galleries using a mix of HTML and CSS.
  • CSS3D Transformations and Animations: Dive into CSS animations, including keyframes, delays, iterations, and 3D transformations to bring movement and engagement to your interfaces.
  • Flexbox and Grid Layouts: Develop flexible, responsive layouts with CSS Flexbox and Grid systems, the modern methods for arranging content that adapts seamlessly to various screen sizes.
  • Media Queries and Responsive Design: Learn to create responsive layouts that work beautifully on desktops, tablets, and smartphones, using media queries tailored for dark mode, high-resolution displays, and print.
  • CSS Variables and Custom Properties: Utilize CSS variables to streamline your code, create dynamic themes, and simplify maintenance.
  • Semantic HTML and SEO Optimization: Employ HTML5 semantic elements, meta tags, and structured data to ensure your content is discoverable by search engines and meaningful to all users.

Basic HTML Document Structure

Description:

This example demonstrates the basic structure of an HTML document, including the <!DOCTYPE html> declaration, <html>, <head>, and <body> tags.

Code:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <title>Basic HTML Document</title>

</head>

<body>

    <h1>Welcome to My Website</h1>

    <p>This is a basic HTML document structure.</p>

</body>

</html>

Explanation:

  • <!DOCTYPE html>: Declares the document type and version of HTML (HTML5).
  • <html lang=”en”>: The root element of the HTML document with the language attribute set to English.
  • : Contains metadata, such as and <meta> tags.
    • <meta charset=”UTF-8″>: Sets the character encoding to UTF-8.
    • <title>: Specifies the title of the webpage, displayed in the browser tab.
  • : Contains all the visible content of the webpage.
    • <h1>: A top-level heading.
    • <p>: A paragraph of text.

Headings and Paragraphs

Description:

This example shows how to use various heading tags (<h1> to <h6>) and paragraphs (<p>).

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Headings and Paragraphs</title>

</head>

<body>

    <h1>Heading Level 1</h1>

    <p>This is a paragraph under heading level 1.</p>

    <h2>Heading Level 2</h2>

    <p>This is a paragraph under heading level 2.</p>

    <h3>Heading Level 3</h3>

    <p>This is a paragraph under heading level 3.</p>

    <h4>Heading Level 4</h4>

    <p>This is a paragraph under heading level 4.</p>

    <h5>Heading Level 5</h5>

    <p>This is a paragraph under heading level 5.</p>

    <h6>Heading Level 6</h6>

    <p>This is a paragraph under heading level 6.</p>

</body>

</html>

Explanation:

  • <h1> to <h6>: Heading tags, with <h1> being the highest level and <h6> the lowest.
  • <p>: Defines a paragraph of text.
  • Headings help structure content and improve SEO and accessibility.

Links and Images

Description:

This example demonstrates how to add hyperlinks and images to an HTML document.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Links and Images</title>

</head>

<body>

    <h1>Links and Images Example</h1>

    <p>Visit <a href=”https://www.example.com”>Example Website</a> for more information.</p>

    <img src=”https://via.placeholder.com/300×200″ alt=”Example Image” width=”300″ height=”200″>

</body>

</html>

Explanation:

  • : Creates a hyperlink to another webpage.
    • href: Specifies the destination URL.
  • description: Embeds an image into the page.
    • src: The path to the image file.
    • alt: Alternative text for accessibility and SEO.
    • width and height: Set the image dimensions.

Lists (Ordered and Unordered)

Description:

This example shows how to create ordered and unordered lists using <ol>, <ul>, and list items <li>.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Lists Example</title>

</head>

<body>

    <h1>Unordered List</h1>

    <ul>

        <li>First item</li>

        <li>Second item</li>

        <li>Third item</li>

    </ul>

    <h1>Ordered List</h1>

    <ol>

        <li>First item</li>

        <li>Second item</li>

        <li>Third item</li>

    </ol>

</body>

</html>

Explanation:

  • <ul>: Creates an unordered (bulleted) list.
  • <ol>: Creates an ordered (numbered) list.
  • <li>: Defines a list item within <ul> or <ol>.

Tables

Description:

This example illustrates how to create a basic table using HTML table elements.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Table Example</title>

</head>

<body>

    <h1>Basic Table</h1>

    <table border=”1″>

        <thead>

            <tr>

                <th>Header 1</th>

                <th>Header 2</th>

            </tr>

        </thead>

        <tbody>

            <tr>

                <td>Row 1, Cell 1</td>

                <td>Row 1, Cell 2</td>

            </tr>

            <tr>

                <td>Row 2, Cell 1</td>

                <td>Row 2, Cell 2</td>

            </tr>

        </tbody>

    </table>

</body>

</html>

Explanation:

  • <table>: Defines a table.
  • <thead> and <tbody>: Group table header and body content.
  • <tr>: Table row.
  • <th>: Header cell.
  • <td>: Standard data cell.
  • border=”1″: Adds a border for visibility.

Forms (Input fields, labels, buttons)

Description:

This example shows how to create a basic HTML form with labels, input fields, and a submit button.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Form Example</title>

</head>

<body>

    <h1>Contact Form</h1>

    <form action=”/submit-form” method=”post”>

        <label for=”name”>Name:</label><br>

        <input type=”text” id=”name” name=”name”><br><br>

        <label for=”email”>Email:</label><br>

        <input type=”email” id=”email” name=”email”><br><br>

        <input type=”submit” value=”Submit”>

    </form>

</body>

</html>

Explanation:

  • : Collects user input.
    • action: URL to send form data.
    • method: HTTP method (get or post).
    • for: Associates the label with an input’s id.
  • : Collects user input.
    • type: Specifies the type of input (e.g., text, email, submit).
  • <input type=”submit”>: A button to submit the form.

Semantic HTML Elements

Description:

This example demonstrates the use of semantic HTML5 elements like <header>, <nav>, <section>, <article>, and <footer> to structure a webpage.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Semantic HTML Example</title>

</head>

<body>

    <header>

        <h1>Website Title</h1>

    </header>

    <nav>

        <ul>

            <li><a href=”#home”>Home</a></li>

            <li><a href=”#about”>About</a></li>

        </ul>

    </nav>

    <main>

        <section>

            <article>

                <h2>Article Title</h2>

                <p>This is an article within a section.</p>

            </article>

        </section>

    </main>

    <footer>

        <p>&copy; 2024 My Website</p>

    </footer>

</body>

</html>

Explanation:

  • Semantic elements provide meaning to the structure:
    • <header>: Top of the page.
    • <nav>: Navigation links.
    • <main>: Main content area.
    • <section>: A thematic grouping of content.
    • <article>: Independent, self-contained content.
    • <footer>: Footer content.

CSS Selectors (Element, Class, ID)

Description:

This example illustrates how to use different CSS selectors to style HTML elements: element selectors, class selectors, and ID selectors.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Selectors Example</title>

    <style>

        /* Element selector */

        p {

            color: blue;

        }

        /* Class selector */

        .highlight {

            background-color: yellow;

        }

        /* ID selector */

        #unique {

            font-weight: bold;

        }

    </style>

</head>

<body>

    <p>This paragraph will be blue.</p>

    <p class=”highlight”>This paragraph will have a yellow background.</p>

    <p id=”unique”>This paragraph will be bold.</p>

</body>

</html>

Explanation:

  • p: Styles all <p> elements.
  • .highlight: Targets elements with class=”highlight”.
  • #unique: Targets the element with id=”unique”.
  • Classes can be reused; IDs are unique.

CSS Box Model (margin, border, padding, content)

Description:

This example demonstrates the CSS box model properties, including margin, border, padding, and width.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Box Model Example</title>

    <style>

        .box {

            width: 200px;

            border: 5px solid black;

            padding: 20px;

            margin: 30px;

            background-color: lightgray;

        }

    </style>

</head>

<body>

    <div class=”box”>

        <p>This box demonstrates the CSS box model.</p>

    </div>

</body>

</html>

Explanation:

  • width: The width of the content area.
  • padding: Space between content and border.
  • border: The border around padding and content.
  • margin: Space outside the border.
  • The box model affects layout and spacing.

CSS Flexbox

Description:

This example shows how to use CSS Flexbox to create a flexible layout that distributes space among items in a container.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Flexbox Example</title>

    <style>

        .container {

            display: flex;

            background-color: lightblue;

        }

        .item {

            background-color: coral;

            padding: 20px;

            margin: 10px;

            flex: 1;

        }

    </style>

</head>

<body>

    <div class=”container”>

        <div class=”item”>Flex Item 1</div>

        <div class=”item”>Flex Item 2</div>

        <div class=”item”>Flex Item 3</div>

    </div>

</body>

</html>

Explanation:

  • display: flex;: Turns the container into a flex container.
  • flex: 1;: Makes flex items grow equally to fill space.
  • Flexbox allows responsive and flexible layouts.

CSS Grid

Description:

This example demonstrates how to use CSS Grid to create a two-dimensional layout.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Grid Example</title>

    <style>

        .grid-container {

            display: grid;

            grid-template-columns: auto auto auto;

            gap: 10px;

            background-color: #2196F3;

            padding: 10px;

        }

        .grid-item {

            background-color: rgba(255,255,255,0.8);

            padding: 20px;

            text-align: center;

            font-size: 30px;

        }

    </style>

</head>

<body>

    <div class=”grid-container”>

        <div class=”grid-item”>1</div>

        <div class=”grid-item”>2</div>

        <div class=”grid-item”>3</div>  

        <div class=”grid-item”>4</div>

        <div class=”grid-item”>5</div>

        <div class=”grid-item”>6</div>  

    </div>

</body>

</html>

Explanation:

  • display: grid;: Defines a grid container.
  • grid-template-columns: Specifies the number and size of columns.
  • gap: Sets the spacing between grid items.

Styling Text (fonts, colors, text alignment)

Description:

This example shows how to style text using CSS properties like font-family, color, font-size, and text-align.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Styling Text Example</title>

    <style>

        h1 {

            font-family: ‘Arial, sans-serif’;

            color: darkblue;

            text-align: center;

        }

        p {

            font-size: 18px;

            line-height: 1.6;

            color: #333333;

        }

    </style>

</head>

<body>

    <h1>Styled Heading</h1>

    <p>This is a paragraph with styled text. The font size, line height, and color have been customized.</p>

</body>

</html>

Explanation:

  • font-family: Specifies the font.
  • color: Text color.
  • font-size: Size of the text.
  • text-align: Horizontal alignment.

Background Images and Colors

Description:

This example illustrates how to set background images and colors using CSS.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Background Example</title>

    <style>

        body {

            background-color: #f0f0f0;

        }

        .background-image {

            background-image: url(‘https://via.placeholder.com/800×400’);

            background-repeat: no-repeat;

            background-size: cover;

            height: 400px;

            color: white;

            text-align: center;

            padding-top: 150px;

        }

    </style>

</head>

<body>

    <div class=”background-image”>

        <h1>Background Image Example</h1>

    </div>

</body>

</html>

Explanation:

  • background-image: Sets an image as the background.
  • background-size: cover;: Scales the image to cover the container.
  • background-repeat: no-repeat;: Prevents the image from repeating.

Positioning (static, relative, absolute, fixed, sticky)

Description:

This example demonstrates different CSS positioning methods.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Positioning Example</title>

    <style>

        .relative {

            position: relative;

            left: 20px;

            background-color: lightgreen;

            padding: 10px;

        }

        .absolute {

            position: absolute;

            top: 50px;

            left: 50px;

            background-color: lightcoral;

            padding: 10px;

        }

        .fixed {

            position: fixed;

            bottom: 0;

            width: 100%;

            background-color: lightblue;

            text-align: center;

            padding: 10px;

        }

    </style>

</head>

<body>

    <div class=”relative”>

        This is a relative positioned element.

    </div>

    <div class=”absolute”>

        This is an absolute positioned element.

    </div>

    <div class=”fixed”>

        This is a fixed positioned footer.

    </div>

</body>

</html>

Explanation:

  • position: relative;: Positioned relative to its normal position.
  • position: absolute;: Positioned relative to its first positioned ancestor.
  • position: fixed;: Positioned relative to the viewport.

Responsive Design with Media Queries

Description:

This example shows how to use media queries to create a responsive design that adjusts to different screen sizes.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Responsive Design Example</title>

    <style>

        .responsive {

            background-color: lightgray;

            padding: 20px;

            text-align: center;

        }

        @media (max-width: 600px) {

            .responsive {

                background-color: lightcoral;

                font-size: 18px;

            }

        }

    </style>

</head>

<body>

    <div class=”responsive”>

        Resize the browser window to see the effect!

    </div>

</body>

</html>

Explanation:

  • @media (max-width: 600px): Applies styles when the viewport is 600px or narrower.
  • Responsive design ensures the webpage looks good on all devices.

Transitions and Animations

Description:

This example demonstrates how to create a hover effect using CSS transitions.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Transitions Example</title>

    <style>

        .box {

            width: 200px;

            height: 200px;

            background-color: salmon;

            transition: background-color 0.5s, transform 0.5s;

        }

        .box:hover {

            background-color: seagreen;

            transform: scale(1.2);

        }

    </style>

</head>

<body>

    <div class=”box”></div>

</body>

</html>

Explanation:

  • transition: Specifies which properties to animate and the duration.
  • On :hover, the box changes color and scales up smoothly.

Pseudo-classes and Pseudo-elements (

, ::before)

Description:

This example shows how to use CSS pseudo-classes and pseudo-elements to style elements in different states or insert content.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Pseudo-classes and Pseudo-elements Example</title>

    <style>

        a {

            color: blue;

            text-decoration: none;

        }

        a:hover {

            color: red;

        }

        p::first-letter {

            font-size: 2em;

            color: green;

        }

    </style>

</head>

<body>

    <a href=”#”>Hover over this link</a>

    <p>This paragraph uses a pseudo-element to style the first letter.</p>

</body>

</html>

Explanation:

  • :hover: Styles applied when the user hovers over an element.
  • ::first-letter: Styles the first letter of a block element.

Inline vs External CSS

Description:

This example compares the use of inline styles, internal styles (within <style>), and external CSS files.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Inline vs External CSS Example</title>

    <style>

        /* Internal CSS */

        .internal-style {

            color: blue;

        }

    </style>

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

</head>

<body>

    <p style=”color: red;”>This paragraph uses inline CSS.</p>

    <p class=”internal-style”>This paragraph uses internal CSS.</p>

    <p class=”external-style”>This paragraph uses external CSS.</p>

</body>

</html>

External CSS (styles.css):

css

/* External CSS */

.external-style {

    color: green;

}

Explanation:

  • Inline CSS: Defined within the style attribute.
  • Internal CSS: Defined within the <style> tag.
  • External CSS: Linked via <link> and defined in a separate file.
  • External CSS is preferred for maintainability.

CSS Variables (Custom Properties)

Description:

This example shows how to use CSS variables to store values that can be reused throughout the stylesheet.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Variables Example</title>

    <style>

        :root {

            –main-bg-color: lightblue;

            –main-text-color: darkblue;

        }

        body {

            background-color: var(–main-bg-color);

            color: var(–main-text-color);

        }

        .box {

            border: 2px solid var(–main-text-color);

            padding: 20px;

        }

    </style>

</head>

<body>

    <div class=”box”>

        <p>This example uses CSS variables for colors.</p>

    </div>

</body>

</html>

Explanation:

  • :root: Declares global CSS variables.
  • var(–variable-name): References a variable.
  • Variables make it easy to update styles globally.

CSS Specificity and Inheritance

Description:

This example demonstrates how CSS specificity and inheritance affect which styles are applied to elements.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Specificity Example</title>

    <style>

        p {

            color: black;

        }

        .special {

            color: green;

        }

        #unique {

            color: red;

        }

    </style>

</head>

<body>

    <p>This paragraph is black.</p>

    <p class=”special”>This paragraph is green.</p>

    <p id=”unique”>This paragraph is red.</p>

    <p class=”special” id=”unique”>Which color is this paragraph?</p>

</body>

</html>

Explanation:

  • Specificity hierarchy: ID selectors > Class selectors > Element selectors.
  • The last paragraph has both class and id; the ID style takes precedence.

CSS Transformations (rotate, scale)

Description:

This example shows how to use CSS transformations to rotate and scale elements.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Transformations Example</title>

    <style>

        .transform-box {

            width: 100px;

            height: 100px;

            background-color: lightseagreen;

            margin: 50px;

            transition: transform 0.5s;

        }

        .transform-box:hover {

            transform: rotate(45deg) scale(1.5);

        }

    </style>

</head>

<body>

    <div class=”transform-box”></div>

</body>

</html>

Explanation:

  • transform: rotate(45deg) scale(1.5);: Rotates and scales the element.
  • transition: Smooths the transformation.

Building a Navigation Bar

Description:

This example demonstrates how to build a horizontal navigation bar with CSS styling.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Navigation Bar Example</title>

    <style>

        ul.navbar {

            list-style-type: none;

            margin: 0;

            padding: 0;

            background-color: #333;

            overflow: hidden;

        }

        ul.navbar li {

            float: left;

        }

        ul.navbar li a {

            display: block;

            color: white;

            text-align: center;

            padding: 14px 16px;

            text-decoration: none;

        }

        ul.navbar li a:hover {

            background-color: #111;

        }

    </style>

</head>

<body>

    <ul class=”navbar”>

        <li><a href=”#home”>Home</a></li>

        <li><a href=”#services”>Services</a></li>

        <li><a href=”#contact”>Contact</a></li>

    </ul>

</body>

</html>

Explanation:

  • float: left;: Aligns list items horizontally.
  • Links are styled to fill the list items and change on hover.

Styling Forms

Description:

This example shows how to style form elements like inputs, labels, and buttons.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Styling Forms Example</title>

    <style>

        form {

            max-width: 400px;

            margin: auto;

        }

        label {

            display: block;

            margin-top: 15px;

            font-weight: bold;

        }

        input[type=”text”], input[type=”email”], textarea {

            width: 100%;

            padding: 10px;

            margin-top: 5px;

            border: 1px solid #ccc;

            border-radius: 4px;

        }

        input[type=”submit”] {

            margin-top: 20px;

            background-color: darkblue;

            color: white;

            padding: 10px 15px;

            border: none;

            border-radius: 4px;

            cursor: pointer;

        }

        input[type=”submit”]:hover {

            background-color: navy;

        }

    </style>

</head>

<body>

    <form action=”/submit-form” method=”post”>

        <label for=”fname”>First Name:</label>

        <input type=”text” id=”fname” name=”firstname”>

        <label for=”email”>Email:</label>

        <input type=”email” id=”email” name=”email”>

        <label for=”message”>Message:</label>

        <textarea id=”message” name=”message” rows=”5″></textarea>

        <input type=”submit” value=”Submit”>

    </form>

</body>

</html>

Explanation:

  • Inputs and textarea are styled for better user experience.
  • Submit button changes color on hover.

Using Google Fonts

Description:

This example demonstrates how to use Google Fonts to import and apply custom fonts to your webpage.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Google Fonts Example</title>

    <link rel=”stylesheet” href=”https://fonts.googleapis.com/css?family=Roboto|Lobster”>

    <style>

        h1 {

            font-family: ‘Lobster’, cursive;

        }

        p {

            font-family: ‘Roboto’, sans-serif;

        }

    </style>

</head>

<body>

    <h1>Custom Font Heading</h1>

    <p>This paragraph uses the Roboto font from Google Fonts.</p>

</body>

</html>

Explanation:

  • <link> tag imports fonts from Google Fonts.
  • font-family: Applies the imported fonts to elements.

Implementing a Simple CSS Reset

Description:

This example shows how to implement a simple CSS reset to remove default browser styles.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Reset Example</title>

    <style>

        /* Simple CSS Reset */

        * {

            margin: 0;

            padding: 0;

            box-sizing: border-box;

        }

        body {

            font-family: Arial, sans-serif;

            padding: 20px;

        }

        h1 {

            margin-bottom: 15px;

        }

        p {

            margin-bottom: 10px;

        }

    </style>

</head>

<body>

    <h1>CSS Reset Applied</h1>

    <p>This example demonstrates how a CSS reset removes default margins and paddings.</p>

    <p>Custom styles are then added for consistent spacing.</p>

</body>

</html>

Explanation:

  • *: Universal selector resets margin and padding.
  • box-sizing: border-box;: Includes padding and border in element’s total width and height.
  • Helps ensure consistent styling across browsers.

HTML5 Audio Element

Description:

This example demonstrates how to embed audio files into a webpage using the HTML5 <audio> element.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>HTML5 Audio Example</title>

</head>

<body>

    <h1>Audio Playback</h1>

    <audio controls>

        <source src=”audio-file.mp3″ type=”audio/mpeg”>

        <source src=”audio-file.ogg” type=”audio/ogg”>

        Your browser does not support the audio element.

    </audio>

</body>

</html>

Explanation:

  • <audio controls>: Embeds an audio player with playback controls.
  • : Specifies the audio file and its format.
    • src: Path to the audio file.
    • type: MIME type of the audio file.
  • Multiple <source> elements provide fallback options for different browsers.
  • The text inside <audio> is displayed if the browser doesn’t support the element.

HTML5 Video Element

Description:

This example shows how to embed video files into a webpage using the HTML5 <video> element.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>HTML5 Video Example</title>

</head>

<body>

    <h1>Video Playback</h1>

    <video width=”640″ height=”360″ controls>

        <source src=”video-file.mp4″ type=”video/mp4″>

        <source src=”video-file.webm” type=”video/webm”>

        Your browser does not support the video tag.

    </video>

</body>

</html>

Explanation:

    • width and height: Dimensions of the video player.
    • controls: Displays playback controls.
  • <source>: Specifies video files in different formats.
  • Provides alternative content if the browser doesn’t support <video>.

Embedding YouTube Videos

Description:

This example demonstrates how to embed a YouTube video into a webpage using an <iframe>.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Embedding YouTube Video</title>

</head>

<body>

    <h1>YouTube Video Embed</h1>

    <iframe width=”560″ height=”315″ src=”https://www.youtube.com/embed/VIDEO_ID” 

            title=”YouTube video player” frameborder=”0″ allowfullscreen>

    </iframe>

</body>

</html>

Explanation:

    • src: The URL of the YouTube video with /embed/VIDEO_ID.
    • width and height: Dimensions of the video player.
    • allowfullscreen: Allows full-screen mode.
  • Replace VIDEO_ID with the actual YouTube video ID.

Using SVG Graphics

Description:

This example shows how to include Scalable Vector Graphics (SVG) directly in HTML.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>SVG Graphics Example</title>

</head>

<body>

    <h1>SVG Circle</h1>

    <svg width=”200″ height=”200″>

        <circle cx=”100″ cy=”100″ r=”80″ stroke=”green” stroke-width=”4″ fill=”yellow” />

    </svg>

</body>

</html>

Explanation:

  • : Defines an SVG container.
    • width and height: Dimensions of the SVG area.
  • : Draws a circle.
    • cx, cy: Center coordinates.
    • r: Radius.
    • stroke: Border color.
    • stroke-width: Border thickness.
    • fill: Fill color.
  • SVG allows for resolution-independent graphics.

HTML Canvas Element

Description:

This example demonstrates how to draw shapes using the HTML <canvas> element and JavaScript.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Canvas Drawing Example</title>

</head>

<body>

    <h1>Canvas Rectangle</h1>

    <canvas id=”myCanvas” width=”200″ height=”100″ style=”border:1px solid #000000;”>

    </canvas>

    <script>

        var canvas = document.getElementById(‘myCanvas’);

        var ctx = canvas.getContext(‘2d’);

        ctx.fillStyle = ‘blue’;

        ctx.fillRect(20, 20, 150, 50);

    </script>

</body>

</html>

Explanation:

  • : Creates a drawing area.
    • id: Identifier to access via JavaScript.
  • JavaScript:
    • getContext(‘2d’): Gets the 2D drawing context.
    • fillStyle: Sets fill color.
    • fillRect(x, y, width, height): Draws a filled rectangle.
  • The canvas element requires JavaScript to render graphics.

Using iframes

Description:

This example illustrates how to embed another webpage within the current page using <iframe>.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Iframe Example</title>

</head>

<body>

    <h1>Embedded Webpage</h1>

    <iframe src=”https://www.example.com” width=”600″ height=”400″ title=”Embedded Page”>

        Your browser does not support iframes.

    </iframe>

</body>

</html>

Explanation:

    • src: URL of the page to embed.
    • width and height: Dimensions of the iframe.
    • title: Describes the iframe content for accessibility.
  • Useful for embedding external content.

CSS Keyframe Animations

Description:

This example demonstrates how to create animations using CSS @keyframes.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Animation Example</title>

    <style>

        .animated-box {

            width: 100px;

            height: 100px;

            background-color: red;

            position: relative;

            animation-name: slide;

            animation-duration: 4s;

            animation-iteration-count: infinite;

        }

        @keyframes slide {

            0% { left: 0px; }

            50% { left: 200px; }

            100% { left: 0px; }

        }

    </style>

</head>

<body>

    <div class=”animated-box”></div>

</body>

</html>

Explanation:

  • @keyframes: Defines the animation.
    • Specifies styles at various points (0%, 50%, 100%).
  • .animated-box:
    • animation-name: References the @keyframes animation.
    • animation-duration: Length of one cycle.
    • animation-iteration-count: Number of times the animation repeats.
  • The box moves horizontally back and forth.

Creating a Modal Popup with HTML and CSS

Description:

This example shows how to create a simple modal popup window using HTML and CSS.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Modal Popup Example</title>

    <style>

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

        /* The Modal (background) */

        .modal {

            display: none; 

            position: fixed; 

            z-index: 1;

            left: 0; top: 0;

            width: 100%; height: 100%;

            overflow: auto; 

            background-color: rgba(0,0,0,0.5); 

        }

        /* Modal Content */

        .modal-content {

            background-color: #fefefe;

            margin: 15% auto; 

            padding: 20px;

            border: 1px solid #888;

            width: 80%; 

        }

        /* Close Button */

        .close {

            color: #aaa;

            float: right;

            font-size: 28px; font-weight: bold;

        }

        .close:hover,

        .close:focus {

            color: black; text-decoration: none; cursor: pointer;

        }

    </style>

</head>

<body>

<h2>Modal Popup Example</h2>

<!– Trigger/Open The Modal –>

<button id=”openModalBtn”>Open Modal</button>

<!– The Modal –>

<div id=”myModal” class=”modal”>

  <!– Modal content –>

  <div class=”modal-content”>

    <span class=”close”>&times;</span>

    <p>This is a modal popup!</p>

  </div>

</div>

<script>

    var modal = document.getElementById(‘myModal’);

    var btn = document.getElementById(‘openModalBtn’);

    var span = document.getElementsByClassName(‘close’)[0];

    btn.onclick = function() { modal.style.display = ‘block’; }

    span.onclick = function() { modal.style.display = ‘none’; }

    window.onclick = function(event) {

        if (event.target == modal) { modal.style.display = ‘none’; }

    }

</script>

</body>

</html>

Explanation:

  • .modal: Hidden by default; covers the entire screen.
  • .modal-content: Centered content box.
  • .close: Styled close button (×).
  • JavaScript handles opening and closing the modal.
    • Shows modal on button click.
    • Hides modal when clicking the close button or outside the modal.

CSS Sprites

Description:

This example demonstrates how to use CSS sprites to display multiple images efficiently.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Sprites Example</title>

    <style>

        .sprite {

            background-image: url(‘sprite-image.png’);

            display: inline-block;

        }

        .icon1 {

            width: 50px; height: 50px;

            background-position: 0 0;

        }

        .icon2 {

            width: 50px; height: 50px;

            background-position: -50px 0;

        }

        .icon3 {

            width: 50px; height: 50px;

            background-position: -100px 0;

        }

    </style>

</head>

<body>

    <div class=”sprite icon1″></div>

    <div class=”sprite icon2″></div>

    <div class=”sprite icon3″></div>

</body>

</html>

Explanation:

  • background-image: Uses a single image containing multiple icons.
  • background-position: Shifts the visible area to display the desired icon.
  • Reduces the number of HTTP requests by combining images.

CSS Shapes

Description:

This example shows how to create non-rectangular shapes using CSS.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Shapes Example</title>

    <style>

        .circle {

            width: 100px; height: 100px;

            background-color: red;

            border-radius: 50%;

        }

        .triangle {

            width: 0; height: 0;

            border-left: 50px solid transparent;

            border-right: 50px solid transparent;

            border-bottom: 100px solid blue;

        }

    </style>

</head>

<body>

    <div class=”circle”></div>

    <div class=”triangle”></div>

</body>

</html>

Explanation:

  • .circle: Uses border-radius: 50%; to create a circle.
  • .triangle: Creates a triangle using borders.
    • Zero width and height.
    • Borders on the sides are transparent.
    • Bottom border is colored, forming a triangle.

CSS Variables with JavaScript

Description:

This example demonstrates how to manipulate CSS variables using JavaScript.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Variables with JavaScript Example</title>

    <style>

        :root {

            –bg-color: lightblue;

        }

        body {

            background-color: var(–bg-color);

        }

    </style>

</head>

<body>

    <button onclick=”changeColor()”>Change Background Color</button>

    <script>

        function changeColor() {

            var root = document.querySelector(‘:root’);

            root.style.setProperty(‘–bg-color’, ‘lightgreen’);

        }

    </script>

</body>

</html>

Explanation:

  • :root: Defines a CSS variable –bg-color.
  • body: Uses the variable for background color.
  • JavaScript:
    • Selects the root element.
    • Updates the CSS variable using setProperty.
    • Changes the background color when the button is clicked.

Responsive Image Gallery

Description:

This example shows how to create a responsive image gallery that adjusts to screen size.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Responsive Image Gallery</title>

    <style>

        .gallery {

            display: flex;

            flex-wrap: wrap;

        }

        .gallery img {

            width: 100%;

            max-width: 200px;

            margin: 5px;

        }

        @media (max-width: 600px) {

            .gallery img {

                max-width: 100px;

            }

        }

    </style>

</head>

<body>

    <h1>Image Gallery</h1>

    <div class=”gallery”>

        <img src=”image1.jpg” alt=”Image 1″>

        <img src=”image2.jpg” alt=”Image 2″>

        <!– Add more images as needed –>

    </div>

</body>

</html>

Explanation:

  • .gallery: Uses Flexbox to wrap images.
  • Images adjust size based on viewport width.
  • Media query reduces image size on small screens.

CSS Filter Effects

Description:

This example demonstrates how to apply filter effects to images using CSS.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Filter Effects Example</title>

    <style>

        img {

            width: 300px;

            height: auto;

            transition: filter 0.5s;

        }

        img:hover {

            filter: grayscale(100%) blur(2px);

        }

    </style>

</head>

<body>

    <h1>Hover over the image</h1>

    <img src=”image.jpg” alt=”Sample Image”>

</body>

</html>

Explanation:

  • filter: Applies visual effects like grayscale and blur.
  • On hover, the image turns grayscale and blurs slightly.
  • transition smooths the effect.

CSS Blend Modes

Description:

This example shows how to use CSS mix-blend-mode to blend an element with its background.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Blend Modes Example</title>

    <style>

        body {

            background-image: url(‘background.jpg’);

            background-size: cover;

        }

        h1 {

            color: white;

            mix-blend-mode: difference;

            font-size: 50px;

            text-align: center;

            padding-top: 200px;

        }

    </style>

</head>

<body>

    <h1>Blended Text</h1>

</body>

</html>

Explanation:

  • mix-blend-mode: Determines how an element’s content blends with its background.
  • difference: Inverts the background color where the text overlaps.
  • Creates visually interesting effects.

CSS-only Tooltip

Description:

This example demonstrates how to create tooltips using only CSS.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Tooltip Example</title>

    <style>

        .tooltip {

            position: relative;

            display: inline-block;

            cursor: pointer;

        }

        .tooltip .tooltiptext {

            visibility: hidden;

            width: 120px;

            background-color: black; color: #fff;

            text-align: center; padding: 5px 0;

            border-radius: 6px;

            position: absolute; z-index: 1;

            bottom: 125%; left: 50%; margin-left: -60px;

            opacity: 0; transition: opacity 0.3s;

        }

        .tooltip:hover .tooltiptext {

            visibility: visible; opacity: 1;

        }

    </style>

</head>

<body>

    <div class=”tooltip”>Hover over me

        <span class=”tooltiptext”>Tooltip text</span>

    </div>

</body>

</html>

Explanation:

  • .tooltip: Wrapper for the tooltip.
  • .tooltiptext: Hidden by default.
  • On hover, the tooltip text becomes visible.
  • No JavaScript is needed.

CSS Counters

Description:

This example shows how to use CSS counters to automatically number elements.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Counters Example</title>

    <style>

        ol {

            counter-reset: item;

            list-style-type: none;

        }

        li::before {

            counter-increment: item;

            content: counter(item) “. “;

            font-weight: bold;

        }

    </style>

</head>

<body>

    <h1>Numbered List with CSS Counters</h1>

    <ol>

        <li>First item</li>

        <li>Second item</li>

        <li>Third item</li>

    </ol>

</body>

</html>

Explanation:

  • counter-reset: Initializes a counter.
  • counter-increment: Increments the counter.
  • content: counter(item): Inserts the counter value before each list item.
  • Customizes numbering beyond default list styles.

CSS Clipping and Masking

Description:

This example demonstrates how to clip an image into a custom shape using CSS clip-path.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Clipping Example</title>

    <style>

        .clip-circle {

            width: 200px;

            height: 200px;

            background-image: url(‘image.jpg’);

            background-size: cover;

            clip-path: circle(50% at 50% 50%);

        }

    </style>

</head>

<body>

    <h1>Clipped Image</h1>

    <div class=”clip-circle”></div>

</body>

</html>

Explanation:

  • clip-path: Clips an element to a specific shape.
  • circle(50% at 50% 50%): Creates a circular clip at the center.
  • Can create various shapes like polygons or ellipses.

CSS Multi-column Layout

Description:

This example shows how to create a multi-column text layout using CSS.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Multi-column Example</title>

    <style>

        .multicolumn {

            column-count: 3;

            column-gap: 20px;

        }

    </style>

</head>

<body>

    <h1>Multi-column Text</h1>

    <div class=”multicolumn”>

        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla facilisi. Integer ac felis auctor, volutpat ligula sit amet, faucibus elit. Suspendisse potenti.</p>

    </div>

</body>

</html>

Explanation:

  • column-count: Specifies the number of columns.
  • column-gap: Sets the space between columns.
  • Automatically flows text into columns.

Using Data Attributes

Description:

This example demonstrates how to use HTML data attributes to store custom data.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Data Attributes Example</title>

</head>

<body>

    <h1>Product List</h1>

    <ul>

        <li data-price=”29.99″>Product A</li>

        <li data-price=”19.99″>Product B</li>

        <li data-price=”49.99″>Product C</li>

    </ul>

    <script>

        var items = document.querySelectorAll(‘li’);

        items.forEach(function(item) {

            var price = item.getAttribute(‘data-price’);

            item.innerHTML += ‘ – $’ + price;

        });

    </script>

</body>

</html>

Explanation:

  • data-* attributes store custom data.
  • JavaScript accesses these attributes using getAttribute.
  • Enhances HTML elements with additional data.

Accessible HTML with ARIA

Description:

This example shows how to use ARIA attributes to improve accessibility.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Accessible HTML Example</title>

</head>

<body>

    <h1>Accessible Navigation</h1>

    <nav aria-label=”Main Navigation”>

        <ul>

            <li><a href=”#home” aria-current=”page”>Home</a></li>

            <li><a href=”#about”>About</a></li>

        </ul>

    </nav>

</body>

</html>

Explanation:

  • aria-label: Provides an accessible name.
  • aria-current=”page”: Indicates the current page in navigation.
  • ARIA attributes help assistive technologies understand the content.

CSS Media Queries for Print

Description:

This example demonstrates how to apply specific styles when printing a webpage.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Print Styles Example</title>

    <style>

        body {

            font-size: 16px;

            color: black;

        }

        @media print {

            body {

                font-size: 12pt;

                color: black;

            }

            .no-print {

                display: none;

            }

        }

    </style>

</head>

<body>

    <h1>Webpage Title</h1>

    <p>This content will be printed.</p>

    <p class=”no-print”>This content will not be printed.</p>

</body>

</html>

Explanation:

  • @media print: Styles applied when the page is printed.
  • Adjusts font size and hides elements not needed in print.
  • Ensures the printed document is formatted correctly.

CSS Calculations with calc()

Description:

This example shows how to perform calculations within CSS properties using calc().

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS calc() Example</title>

    <style>

        .box {

            width: calc(100% – 40px);

            margin: 20px;

            padding: 20px;

            background-color: lightgray;

        }

    </style>

</head>

<body>

    <h1>Box with calc()</h1>

    <div class=”box”>

        <p>The width of this box is calculated using CSS calc().</p>

    </div>

</body>

</html>

Explanation:

  • calc(): Performs calculations for CSS values.
  • In this example, the box’s width adjusts based on the viewport, minus margins.

CSS Combinators

Description:

This example demonstrates how to use CSS combinators to select elements based on their relationship in the DOM.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Combinators Example</title>

    <style>

        /* Descendant combinator */

        ul li {

            color: blue;

        }

        /* Child combinator */

        ul > li {

            font-weight: bold;

        }

        /* Adjacent sibling combinator */

        h2 + p {

            color: red;

        }

        /* General sibling combinator */

        h2 ~ p {

            font-style: italic;

        }

    </style>

</head>

<body>

    <ul>

        <li>List item</li>

    </ul>

    <h2>Heading</h2>

    <p>Paragraph immediately after heading.</p>

    <p>Another paragraph.</p>

</body>

</html>

Explanation:

  • ul li: Selects all <li> elements inside a <ul>.
  • ul > li: Selects immediate child <li> elements of <ul>.
  • h2 + p: Selects the first <p> immediately after <h2>.
  • h2 ~ p: Selects all <p> elements after <h2>.

CSS Attribute Selectors

Description:

This example shows how to select elements based on their attributes using CSS.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Attribute Selectors Example</title>

    <style>

        /* Selects inputs with type=”text” */

        input[type=”text”] {

            background-color: lightyellow;

        }

        /* Selects links starting with “http” */

        a[href^=”http”] {

            color: green;

        }

        /* Selects links ending with “.pdf” */

        a[href$=”.pdf”] {

            color: red;

        }

    </style>

</head>

<body>

    <input type=”text” name=”username”>

    <input type=”password” name=”password”>

    <a href=”http://example.com”>External Link</a>

    <a href=”document.pdf”>PDF Document</a>

</body>

</html>

Explanation:

  • input[type=”text”]: Selects input elements with type=”text”.
  • a[href^=”http”]: Selects links where href starts with http.
  • a[href$=”.pdf”]: Selects links where href ends with .pdf.

CSS3 Text Effects

Description:

This example demonstrates various CSS3 text effects like text-shadow and text-stroke.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Text Effects Example</title>

    <style>

        h1 {

            text-shadow: 2px 2px 4px #000000;

        }

        h2 {

            -webkit-text-stroke: 1px red;

            color: white;

        }

    </style>

</head>

<body>

    <h1>Text Shadow Effect</h1>

    <h2>Text Stroke Effect</h2>

</body>

</html>

Explanation:

  • text-shadow: Adds a shadow to text.
    • 2px 2px 4px #000000: Horizontal offset, vertical offset, blur radius, color.
  • -webkit-text-stroke: Outlines the text with a stroke.
    • Not widely supported; works in WebKit browsers.
  • Creates visually appealing text styles.

HTML Meta Tags for SEO

Description:

This example demonstrates how to use HTML meta tags to improve a webpage’s SEO (Search Engine Optimization) and provide metadata about the document.

Code:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <title>Meta Tags for SEO</title>

    <meta charset=”UTF-8″>

    <meta name=”description” content=”An example showing how to use meta tags for SEO.”>

    <meta name=”keywords” content=”HTML, SEO, Meta Tags, Example”>

    <meta name=”author” content=”Your Name”>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

</head>

<body>

    <h1>Using Meta Tags for SEO</h1>

    <p>This webpage includes meta tags that provide information to search engines.</p>

</body>

</html>

Explanation:

  • <meta charset=”UTF-8″>: Sets the character encoding.
  • <meta name=”description”>: Provides a brief description of the page.
  • <meta name=”keywords”>: Lists relevant keywords.
  • <meta name=”author”>: Specifies the author’s name.
  • <meta name=”viewport”>: Ensures proper rendering on mobile devices.

HTML Entity References

Description:

This example shows how to use HTML entity references to display special characters and symbols.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>HTML Entities Example</title>

</head>

<body>

    <h1>Displaying Special Characters</h1>

    <p>Less than symbol: &lt;</p>

    <p>Greater than symbol: &gt;</p>

    <p>Ampersand: &amp;</p>

    <p>Non-breaking space: &nbsp;</p>

    <p>Registered Trademark: &reg;</p>

    <p>Greek letter alpha: &alpha;</p>

</body>

</html>

Explanation:

  • &lt;: Less than (<)
  • &gt;: Greater than (>)
  • &amp;: Ampersand (&)
  • &nbsp;: Non-breaking space
  • &reg;: Registered trademark symbol
  • &alpha;: Greek letter alpha
  • Entity references start with & and end with ;.

Responsive Images with srcset and sizes

Description:

This example demonstrates how to use the srcset and sizes attributes to serve different images based on the device’s screen size.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Responsive Images Example</title>

</head>

<body>

    <h1>Responsive Image</h1>

    <img src=”small.jpg” 

         srcset=”small.jpg 480w, medium.jpg 800w, large.jpg 1200w” 

         sizes=”(max-width: 600px) 480px, (max-width: 900px) 800px, 1200px” 

         alt=”Responsive Image”>

</body>

</html>

Explanation:

  • srcset: Lists image files with their widths (480w, 800w, 1200w).
  • sizes: Specifies image display sizes based on viewport width.
  • The browser selects the appropriate image file to download.

HTML Details and Summary Elements

Description:

This example shows how to create an expandable/collapsible content section using <details> and <summary>.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Details and Summary Example</title>

</head>

<body>

    <h1>Expandable Content</h1>

    <details>

        <summary>Click to expand</summary>

        <p>This is the hidden content that becomes visible when you click the summary.</p>

    </details>

</body>

</html>

Explanation:

  • <details>: Creates a collapsible section.
  • <summary>: The visible heading that can be clicked to toggle visibility.
  • No JavaScript is required for this functionality.

Progress Bars with HTML and CSS

Description:

This example demonstrates how to create a progress bar using the <progress> element and how to style it with CSS.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Progress Bar Example</title>

    <style>

        progress {

            width: 100%;

            height: 20px;

        }

    </style>

</head>

<body>

    <h1>File Upload Progress</h1>

    <progress value=”70″ max=”100″></progress>

</body>

</html>

Explanation:

  • : Displays a progress bar.
    • value: Current progress value.
    • max: Maximum value (default is 1 if not specified).
  • CSS styles the appearance of the progress bar.

CSS Media Queries for Dark Mode

Description:

This example shows how to use CSS media queries to apply a dark theme when the user’s system is set to dark mode.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Dark Mode Example</title>

    <style>

        body {

            background-color: white;

            color: black;

        }

        @media (prefers-color-scheme: dark) {

            body {

                background-color: black;

                color: white;

            }

        }

    </style>

</head>

<body>

    <h1>Dark Mode Example</h1>

    <p>This page adapts to your system’s color scheme preference.</p>

</body>

</html>

Explanation:

  • @media (prefers-color-scheme: dark): Applies styles when dark mode is preferred.
  • The page automatically switches between light and dark themes.

CSS Flexbox Alignment

Description:

This example demonstrates how to align items within a flex container using justify-content and align-items.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Flexbox Alignment Example</title>

    <style>

        .container {

            display: flex;

            height: 200px;

            background-color: lightgray;

            justify-content: center;

            align-items: center;

        }

        .item {

            background-color: teal;

            color: white;

            padding: 20px;

        }

    </style>

</head>

<body>

    <div class=”container”>

        <div class=”item”>Centered Item</div>

    </div>

</body>

</html>

Explanation:

  • justify-content: center;: Centers items horizontally.
  • align-items: center;: Centers items vertically.
  • Flexbox makes it easy to align content in any direction.

CSS Pseudo-class

()

Description:

This example shows how to select elements based on their position in the DOM using :nth-child().

Code:

<!DOCTYPE html>

<html>

<head>

    <title>:nth-child() Example</title>

    <style>

        li:nth-child(odd) {

            background-color: lightblue;

        }

        li:nth-child(even) {

            background-color: lightgreen;

        }

        li:nth-child(3) {

            font-weight: bold;

        }

    </style>

</head>

<body>

    <h1>Styled List Items</h1>

    <ul>

        <li>Item 1</li>

        <li>Item 2</li>

        <li>Item 3 (Bold)</li>

        <li>Item 4</li>

        <li>Item 5</li>

    </ul>

</body>

</html>

Explanation:

  • :nth-child(odd): Selects odd-numbered elements.
  • :nth-child(even): Selects even-numbered elements.
  • :nth-child(3): Selects the third element specifically.
  • Allows for complex styling patterns.

HTML Input Types

Description:

This example demonstrates various HTML input types for form fields.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>HTML Input Types Example</title>

</head>

<body>

    <h1>Form with Various Input Types</h1>

    <form>

        <label for=”date”>Date:</label>

        <input type=”date” id=”date” name=”date”><br><br>

        <label for=”time”>Time:</label>

        <input type=”time” id=”time” name=”time”><br><br>

        <label for=”number”>Number:</label>

        <input type=”number” id=”number” name=”number” min=”1″ max=”10″><br><br>

        <label for=”range”>Range:</label>

        <input type=”range” id=”range” name=”range” min=”0″ max=”100″><br><br>

        <label for=”color”>Color:</label>

        <input type=”color” id=”color” name=”color”><br><br>

        <input type=”submit” value=”Submit”>

    </form>

</body>

</html>

Explanation:

  • type=”date”: Date picker.
  • type=”time”: Time picker.
  • type=”number”: Numeric input with min and max.
  • type=”range”: Slider control.
  • type=”color”: Color picker.
  • Modern browsers provide appropriate UI controls for these types.

CSS Flexbox Order Property

Description:

This example shows how to change the order of flex items using the order property.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Flexbox Order Example</title>

    <style>

        .container {

            display: flex;

        }

        .item1 {

            order: 3;

        }

        .item2 {

            order: 1;

        }

        .item3 {

            order: 2;

        }

        .item {

            padding: 20px;

            background-color: lightcoral;

            margin: 5px;

        }

    </style>

</head>

<body>

    <h1>Changing Order of Flex Items</h1>

    <div class=”container”>

        <div class=”item item1″>Item 1</div>

        <div class=”item item2″>Item 2</div>

        <div class=”item item3″>Item 3</div>

    </div>

</body>

</html>

Explanation:

  • order: Specifies the order in which flex items appear.
  • Items are displayed in order from lowest to highest order value.
  • Allows for reordering content without changing the HTML structure.

Sticky Navigation Bar

Description:

This example demonstrates how to create a navigation bar that sticks to the top of the viewport when scrolling.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Sticky Navigation Bar Example</title>

    <style>

        .navbar {

            overflow: hidden;

            background-color: #333;

            position: sticky;

            top: 0;

        }

        .navbar a {

            float: left;

            display: block;

            color: white;

            text-align: center;

            padding: 14px 16px;

            text-decoration: none;

        }

        .content {

            padding: 16px;

            height: 2000px; /* For demonstration purposes */

        }

    </style>

</head>

<body>

    <div class=”navbar”>

        <a href=”#home”>Home</a>

        <a href=”#about”>About</a>

    </div>

    <div class=”content”>

        <h1>Scroll Down to See the Sticky Effect</h1>

        <p>The navigation bar will stick to the top when you reach its scroll position.</p>

    </div>

</body>

</html>

Explanation:

  • position: sticky; top: 0;: Makes the navbar stick to the top when scrolling.
  • overflow: hidden;: Ensures that the floating elements are contained.
  • Simplifies creating sticky elements without JavaScript.

HTML5 Semantic Elements (aside, figure, figcaption)

Description:

This example demonstrates the use of <aside>, <figure>, and <figcaption> elements for semantic markup.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Semantic Elements Example</title>

</head>

<body>

    <main>

        <article>

            <h1>Article Title</h1>

            <p>This is the main content of the article.</p>

            <figure>

                <img src=”image.jpg” alt=”Sample Image”>

                <figcaption>Figure 1: A sample image with a caption.</figcaption>

            </figure>

        </article>

        <aside>

            <h2>Related Articles</h2>

            <ul>

                <li><a href=”#link1″>Related Link 1</a></li>

                <li><a href=”#link2″>Related Link 2</a></li>

            </ul>

        </aside>

    </main>

</body>

</html>

Explanation:

  • <figure>: Groups media content with a caption.
  • <figcaption>: Provides a caption for the content within <figure>.
  • <aside>: Contains content indirectly related to the main content.

CSS Grid Template Areas

Description:

This example shows how to use CSS Grid’s grid-template-areas to create a layout.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Grid Template Areas Example</title>

    <style>

        .grid-container {

            display: grid;

            grid-template-areas:

                ‘header header header’

                ‘sidebar content content’

                ‘footer footer footer’;

            grid-gap: 10px;

        }

        .header {

            grid-area: header;

            background-color: lightblue;

        }

        .sidebar {

            grid-area: sidebar;

            background-color: lightgreen;

        }

        .content {

            grid-area: content;

            background-color: lightcoral;

        }

        .footer {

            grid-area: footer;

            background-color: lightgray;

        }

    </style>

</head>

<body>

    <div class=”grid-container”>

        <div class=”header”>Header</div>

        <div class=”sidebar”>Sidebar</div>

        <div class=”content”>Content</div>

        <div class=”footer”>Footer</div>

    </div>

</body>

</html>

Explanation:

  • grid-template-areas: Defines named grid areas.
  • Each area is assigned to a grid item using grid-area.
  • Simplifies complex layouts.

CSS Transitions with Multiple Properties

Description:

This example demonstrates how to apply CSS transitions to multiple properties simultaneously.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Multiple Transitions Example</title>

    <style>

        .box {

            width: 100px;

            height: 100px;

            background-color: skyblue;

            transition: width 2s, background-color 2s;

        }

        .box:hover {

            width: 200px;

            background-color: coral;

        }

    </style>

</head>

<body>

    <h1>Hover over the Box</h1>

    <div class=”box”></div>

</body>

</html>

Explanation:

  • transition: Lists properties to animate and their durations.
  • On hover, both width and background color transition over 2 seconds.

CSS Variables Scoped to Elements

Description:

This example shows how to define CSS variables scoped to specific elements.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Scoped CSS Variables Example</title>

    <style>

        .theme-light {

            –bg-color: white;

            –text-color: black;

        }

        .theme-dark {

            –bg-color: black;

            –text-color: white;

        }

        .box {

            background-color: var(–bg-color);

            color: var(–text-color);

            padding: 20px;

            margin: 10px;

        }

    </style>

</head>

<body>

    <div class=”box theme-light”>

        <p>This is a light-themed box.</p>

    </div>

    <div class=”box theme-dark”>

        <p>This is a dark-themed box.</p>

    </div>

</body>

</html>

Explanation:

  • Variables are defined within .theme-light and .theme-dark.
  • .box uses the variables, which inherit values based on the class.

CSS Background Gradients

Description:

This example demonstrates how to apply linear and radial gradients as background images using CSS.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Background Gradients Example</title>

    <style>

        .linear-gradient {

            height: 100px;

            background: linear-gradient(to right, red, yellow);

            margin-bottom: 20px;

        }

        .radial-gradient {

            height: 100px;

            background: radial-gradient(circle, blue, green);

        }

    </style>

</head>

<body>

    <h1>CSS Background Gradients</h1>

    <div class=”linear-gradient”></div>

    <div class=”radial-gradient”></div>

</body>

</html>

Explanation:

  • linear-gradient: Creates a gradient transitioning between colors along a straight line.
  • radial-gradient: Creates a gradient radiating from the center.
  • Gradients can be used anywhere an image URL is accepted.

CSS Scroll Snap

Description:

This example shows how to implement scroll snapping in a container using CSS.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Scroll Snap Example</title>

    <style>

        .snap-container {

            display: flex;

            overflow-x: scroll;

            scroll-snap-type: x mandatory;

            width: 100%;

        }

        .snap-item {

            flex: 0 0 100%;

            scroll-snap-align: center;

            background-color: lightblue;

            padding: 100px;

            box-sizing: border-box;

            text-align: center;

            font-size: 2em;

        }

    </style>

</head>

<body>

    <h1>Scroll Snap Example</h1>

    <div class=”snap-container”>

        <div class=”snap-item”>Page 1</div>

        <div class=”snap-item”>Page 2</div>

        <div class=”snap-item”>Page 3</div>

    </div>

</body>

</html>

Explanation:

  • scroll-snap-type: x mandatory;: Enables horizontal scroll snapping.
  • scroll-snap-align: center;: Aligns each item to the center during scroll.
  • Creates a smooth, page-like scrolling experience.

CSS Object-fit and Object-position

Description:

This example demonstrates how to control how images fit within their containers using object-fit and object-position.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Object-fit and Object-position Example</title>

    <style>

        .container {

            width: 300px;

            height: 200px;

            overflow: hidden;

            margin-bottom: 20px;

        }

        .fit-cover {

            width: 100%;

            height: 100%;

            object-fit: cover;

        }

        .fit-contain {

            width: 100%;

            height: 100%;

            object-fit: contain;

            background-color: lightgray;

        }

    </style>

</head>

<body>

    <h1>Object-fit and Object-position</h1>

    <div class=”container”>

        <img src=”image.jpg” alt=”Cover” class=”fit-cover”>

    </div>

    <div class=”container”>

        <img src=”image.jpg” alt=”Contain” class=”fit-contain”>

    </div>

</body>

</html>

Explanation:

  • object-fit: cover;: The image fills the container, cropping if necessary.
  • object-fit: contain;: The image scales to fit inside the container, maintaining aspect ratio.
  • Useful for responsive images in fixed-size containers.

CSS Writing Modes

Description:

This example shows how to change the text direction and orientation using CSS writing-mode.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Writing Modes Example</title>

    <style>

        .vertical-rl {

            writing-mode: vertical-rl;

            border: 1px solid black;

            padding: 10px;

            height: 200px;

        }

        .vertical-lr {

            writing-mode: vertical-lr;

            border: 1px solid black;

            padding: 10px;

            height: 200px;

        }

    </style>

</head>

<body>

    <h1>Writing Modes</h1>

    <div class=”vertical-rl”>

        <p>This text flows vertically from right to left.</p>

    </div>

    <div class=”vertical-lr”>

        <p>This text flows vertically from left to right.</p>

    </div>

</body>

</html>

Explanation:

  • writing-mode: vertical-rl;: Text flows vertically from top to bottom and right to left.
  • writing-mode: vertical-lr;: Text flows vertically from top to bottom and left to right.
  • Useful for languages with vertical writing systems.

CSS Box-shadow

Description:

This example demonstrates how to apply shadows to elements using box-shadow.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Box-shadow Example</title>

    <style>

        .box {

            width: 200px;

            height: 200px;

            background-color: white;

            margin: 50px;

            box-shadow: 10px 10px 5px rgba(0,0,0,0.5);

        }

    </style>

</head>

<body>

    <h1>Box Shadow</h1>

    <div class=”box”></div>

</body>

</html>

Explanation:

  • box-shadow: Adds shadow effects around an element’s frame.
    • 10px 10px 5px rgba(0,0,0,0.5): Horizontal offset, vertical offset, blur radius, color.
  • Can create multiple shadows by comma-separating values.

CSS Variables with Fallback Values

Description:

This example shows how to provide fallback values for CSS variables.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Variables Fallback Example</title>

    <style>

        body {

            background-color: var(–bg-color, pink);

            color: var(–text-color, black);

        }

    </style>

</head>

<body>

    <h1>Fallback Values</h1>

    <p>If the CSS variable is not defined, the fallback value is used.</p>

</body>

</html>

Explanation:

  • var(–variable, fallback): Uses the fallback value if –variable is not defined.
  • Ensures styles are applied even if variables are missing.

CSS Animation Delay and Iteration

Description:

This example demonstrates how to use animation-delay and animation-iteration-count in CSS animations.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Animation Delay Example</title>

    <style>

        .animated-box {

            width: 100px;

            height: 100px;

            background-color: coral;

            animation-name: move;

            animation-duration: 2s;

            animation-delay: 1s;

            animation-iteration-count: 3;

            position: relative;

        }

        @keyframes move {

            from { left: 0px; }

            to { left: 200px; }

        }

    </style>

</head>

<body>

    <h1>Animation with Delay and Iterations</h1>

    <div class=”animated-box”></div>

</body>

</html>

Explanation:

  • animation-delay: Waits before starting the animation.
  • animation-iteration-count: Number of times the animation repeats.
  • The box moves to the right, waits 1 second before starting, and repeats 3 times.

HTML Accessible Tables

Description:

This example shows how to make tables more accessible using <caption>, <thead>, <tbody>, and <th> elements.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Accessible Table Example</title>

</head>

<body>

    <h1>Accessible Data Table</h1>

    <table border=”1″>

        <caption>Sales Data</caption>

        <thead>

            <tr>

                <th scope=”col”>Product</th>

                <th scope=”col”>Q1</th>

                <th scope=”col”>Q2</th>

                <th scope=”col”>Q3</th>

                <th scope=”col”>Q4</th>

            </tr>

        </thead>

        <tbody>

            <tr>

                <th scope=”row”>Product A</th>

                <td>100</td>

                <td>150</td>

                <td>130</td>

                <td>170</td>

            </tr>

            <tr>

                <th scope=”row”>Product B</th>

                <td>200</td>

                <td>210</td>

                <td>180</td>

                <td>190</td>

            </tr>

        </tbody>

    </table>

</body>

</html>

Explanation:

  • <caption>: Provides a title for the table.
  • <th scope=”col”>: Indicates header cells for columns.
  • <th scope=”row”>: Indicates header cells for rows.
  • Enhances accessibility for screen readers.

CSS Gradient Text

Description:

This example demonstrates how to apply a gradient to text using background-clip.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Gradient Text Example</title>

    <style>

        h1 {

            font-size: 72px;

            background: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet);

            -webkit-background-clip: text;

            -webkit-text-fill-color: transparent;

        }

    </style>

</head>

<body>

    <h1>Gradient Text</h1>

</body>

</html>

Explanation:

  • background: Applies a gradient background.
  • -webkit-background-clip: text;: Clips the background to the text.
  • -webkit-text-fill-color: transparent;: Makes the text fill transparent so the background shows.
  • Note: This technique may require vendor prefixes and has limited support.

CSS Variable Fonts

Description:

This example shows how to use variable fonts in CSS to adjust font properties dynamically.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Variable Fonts Example</title>

    <style>

        @font-face {

            font-family: ‘Roboto Flex’;

            src: url(‘RobotoFlex-VariableFont_wght.ttf’) format(‘truetype’);

        }

        .variable-font {

            font-family: ‘Roboto Flex’, sans-serif;

            font-variation-settings: ‘wght’ 400, ‘wdth’ 100;

        }

        .variable-font:hover {

            font-variation-settings: ‘wght’ 700, ‘wdth’ 75;

        }

    </style>

</head>

<body>

    <h1>Variable Fonts</h1>

    <p class=”variable-font”>Hover over this text to see the variable font change.</p>

</body>

</html>

Explanation:

  • @font-face: Defines a variable font.
  • font-variation-settings: Adjusts font axes like weight (wght) and width (wdth).
  • On hover, the font changes dynamically without loading a new font file.

HTML5 Geolocation API

Description:

This example demonstrates how to use the HTML5 Geolocation API to get the user’s current location (latitude and longitude).

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Geolocation API Example</title>

</head>

<body>

    <h1>Find Your Location</h1>

    <button onclick=”getLocation()”>Get Location</button>

    <p id=”location”></p>

    <script>

        function getLocation() {

            var output = document.getElementById(‘location’);

            if (navigator.geolocation) {

                navigator.geolocation.getCurrentPosition(showPosition, showError);

            } else {

                output.innerHTML = “Geolocation is not supported by this browser.”;

            }

        }

        function showPosition(position) {

            output.innerHTML = “Latitude: ” + position.coords.latitude + 

                               “<br>Longitude: ” + position.coords.longitude;

        }

        function showError(error) {

            switch(error.code) {

                case error.PERMISSION_DENIED:

                    output.innerHTML = “User denied the request for Geolocation.”;

                    break;

                case error.POSITION_UNAVAILABLE:

                    output.innerHTML = “Location information is unavailable.”;

                    break;

                case error.TIMEOUT:

                    output.innerHTML = “The request to get user location timed out.”;

                    break;

                case error.UNKNOWN_ERROR:

                    output.innerHTML = “An unknown error occurred.”;

                    break;

            }

        }

    </script>

</body>

</html>

Explanation:

  • navigator.geolocation: Accesses the Geolocation API.
  • getCurrentPosition(): Retrieves the user’s current position.
    • showPosition: Callback function to handle the position data.
    • showError: Callback function to handle errors.
  • position.coords.latitude and position.coords.longitude: Provide the geographic coordinates.
  • Error handling provides feedback if the user denies permission or if there are other issues.

HTML5 Web Storage (localStorage and sessionStorage)

Description:

This example demonstrates how to use the Web Storage API to store data locally in the user’s browser using localStorage.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Web Storage Example</title>

</head>

<body>

    <h1>Web Storage Demo</h1>

    <input type=”text” id=”name” placeholder=”Enter your name”>

    <button onclick=”saveName()”>Save Name</button>

    <button onclick=”loadName()”>Load Name</button>

    <p id=”output”></p>

    <script>

        function saveName() {

            var name = document.getElementById(‘name’).value;

            localStorage.setItem(‘userName’, name);

            document.getElementById(‘output’).innerHTML = “Name saved!”;

        }

        function loadName() {

            var name = localStorage.getItem(‘userName’);

            if (name) {

                document.getElementById(‘output’).innerHTML = “Welcome back, ” + name + “!”;

            } else {

                document.getElementById(‘output’).innerHTML = “No name found.”;

            }

        }

    </script>

</body>

</html>

Explanation:

  • localStorage: Stores data with no expiration date.
  • setItem(‘key’, ‘value’): Saves data to localStorage.
  • getItem(‘key’): Retrieves data from localStorage.
  • Data persists even after the browser is closed and reopened.

CSS 3D Transformations

Description:

This example shows how to apply 3D transformations to elements using CSS transform property.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>3D Transformations Example</title>

    <style>

        .cube {

            width: 100px;

            height: 100px;

            background-color: lightblue;

            margin: 100px auto;

            transform: perspective(400px) rotateY(45deg) rotateX(20deg);

        }

    </style>

</head>

<body>

    <h1>3D Transformation</h1>

    <div class=”cube”></div>

</body>

</html>

Explanation:

  • transform: perspective(400px) rotateY(45deg) rotateX(20deg);:
    • perspective: Sets the perspective from which the element is viewed.
    • rotateY: Rotates the element around the Y-axis.
    • rotateX: Rotates the element around the X-axis.
  • Creates a 3D effect where the element appears to be tilted in 3D space.

CSS Media Queries for High-Resolution Displays

Description:

This example demonstrates how to use media queries to serve high-resolution images on devices with high pixel density (e.g., Retina displays).

Code:

<!DOCTYPE html>

<html>

<head>

    <title>High-Resolution Images Example</title>

    <style>

        .image {

            width: 300px;

            height: 200px;

            background-image: url(‘image-normal.png’);

            background-size: cover;

        }

        @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {

            .image {

                background-image: url(‘image-retina.png’);

            }

        }

    </style>

</head>

<body>

    <h1>High-Resolution Image</h1>

    <div class=”image”></div>

</body>

</html>

Explanation:

  • @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi): Targets devices with a pixel ratio of 2 or more.
  • The .image background changes to a higher-resolution image when viewed on high-resolution displays.
  • Ensures images look sharp on all devices.

CSS Sticky Footer

Description:

This example shows how to create a footer that sticks to the bottom of the viewport when the content is short but stays below the content when there’s enough content to fill the page.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Sticky Footer Example</title>

    <style>

        html, body {

            height: 100%;

            margin: 0;

        }

        .wrapper {

            min-height: 100%;

            display: flex;

            flex-direction: column;

        }

        .content {

            flex: 1;

        }

        .footer {

            background-color: lightgray;

            text-align: center;

            padding: 10px;

        }

    </style>

</head>

<body>

    <div class=”wrapper”>

        <div class=”content”>

            <h1>Page Content</h1>

            <p>This is the main content area.</p>

        </div>

        <div class=”footer”>

            <p>Sticky Footer</p>

        </div>

    </div>

</body>

</html>

Explanation:

  • html, body { height: 100%; }: Ensures the body fills the viewport height.
  • .wrapper { display: flex; flex-direction: column; min-height: 100%; }: Sets up a flex container that spans the full height.
  • .content { flex: 1; }: Allows the content to grow and fill available space.
  • The footer stays at the bottom when content is short and moves down as content grows.

CSS z-index and Stacking Contexts

Description:

This example demonstrates how to control the stacking order of overlapping elements using z-index.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>z-index Example</title>

    <style>

        .box1, .box2, .box3 {

            width: 200px;

            height: 200px;

            position: absolute;

        }

        .box1 {

            background-color: red;

            left: 50px;

            top: 50px;

            z-index: 1;

        }

        .box2 {

            background-color: green;

            left: 100px;

            top: 100px;

            z-index: 2;

        }

        .box3 {

            background-color: blue;

            left: 150px;

            top: 150px;

            z-index: 3;

        }

    </style>

</head>

<body>

    <div class=”box1″></div>

    <div class=”box2″></div>

    <div class=”box3″></div>

</body>

</html>

Explanation:

  • Elements are positioned absolutely and overlap each other.
  • z-index: Determines the stacking order (higher z-index means the element is on top).
  • .box3 (blue) has the highest z-index and appears on top of the others.

CSS Pseudo-classes

Description:

This example shows how to use advanced CSS pseudo-classes to style elements based on their state.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Advanced Pseudo-classes Example</title>

    <style>

        /* Select all buttons except those with class ‘exclude’ */

        button:not(.exclude) {

            background-color: lightgreen;

        }

        /* Style empty paragraphs */

        p:empty {

            background-color: yellow;

            height: 20px;

        }

        /* Style input when focused */

        input:focus {

            border: 2px solid blue;

        }

    </style>

</head>

<body>

    <button>Included Button</button>

    <button class=”exclude”>Excluded Button</button>

    <p>This paragraph has content.</p>

    <p></p>

    <input type=”text” placeholder=”Focus on me”>

</body>

</html>

Explanation:

  • :not(selector): Selects elements that do not match the selector.
  • :empty: Selects elements with no child nodes (including text nodes).
  • :focus: Selects elements that are focused (e.g., clicked into or tabbed to).
  • Demonstrates how to apply styles based on element states.

CSS Text Overflow and White-space Properties

Description:

This example shows how to handle text overflow in elements and control white-space wrapping.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Text Overflow Example</title>

    <style>

        .ellipsis {

            width: 200px;

            white-space: nowrap;

            overflow: hidden;

            text-overflow: ellipsis;

            border: 1px solid black;

        }

        .pre-wrap {

            white-space: pre-wrap;

            border: 1px solid black;

            padding: 5px;

            width: 200px;

        }

    </style>

</head>

<body>

    <h1>Text Overflow and White-space</h1>

    <div class=”ellipsis”>

        This is a long line of text that will be truncated with an ellipsis if it doesn’t fit.

    </div>

    <br>

    <div class=”pre-wrap”>

        This text

        contains line breaks

        and     extra spaces.

    </div>

</body>

</html>

Explanation:

  • .ellipsis:
    • white-space: nowrap;: Prevents text from wrapping.
    • overflow: hidden;: Hides overflow text.
    • text-overflow: ellipsis;: Displays an ellipsis (…) where the text is truncated.
  • .pre-wrap:
    • white-space: pre-wrap;: Preserves white space and line breaks.
    • Useful for displaying code or pre-formatted text.

CSS Scrollbar Styling

Description:

This example demonstrates how to customize the appearance of scrollbars using CSS.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Scrollbar Styling Example</title>

    <style>

        .scrollbox {

            width: 300px;

            height: 100px;

            overflow-y: scroll;

            border: 1px solid black;

        }

        /* WebKit browsers */

        .scrollbox::-webkit-scrollbar {

            width: 12px;

        }

        .scrollbox::-webkit-scrollbar-track {

            background: lightgray;

        }

        .scrollbox::-webkit-scrollbar-thumb {

            background-color: darkgray;

            border-radius: 6px;

            border: 3px solid lightgray;

        }

        /* Firefox */

        .scrollbox {

            scrollbar-width: thin;

            scrollbar-color: darkgray lightgray;

        }

    </style>

</head>

<body>

    <h1>Custom Scrollbar</h1>

    <div class=”scrollbox”>

        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel magna sit amet risus ullamcorper hendrerit. Nullam at bibendum ex. Donec vel neque non mi blandit sollicitudin. Morbi auctor, justo at convallis placerat, tortor libero porttitor arcu, at fermentum arcu neque nec purus.</p>

    </div>

</body>

</html>

Explanation:

  • For WebKit browsers (Chrome, Safari):
    • ::-webkit-scrollbar: Styles the scrollbar.
    • ::-webkit-scrollbar-track: Styles the track.
    • ::-webkit-scrollbar-thumb: Styles the thumb (the draggable part).
  • For Firefox:
    • scrollbar-width: Sets the width (auto, thin, none).
    • scrollbar-color: Sets the thumb and track colors.
  • Note: Scrollbar styling is limited and varies between browsers.

CSS List Styling (list-style-image, list-style-position)

Description:

This example shows how to customize list bullets using images and adjust their positions.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>List Styling Example</title>

    <style>

        ul.custom-list {

            list-style-image: url(‘bullet.png’);

            list-style-position: inside;

        }

        ol.custom-list {

            list-style-type: upper-roman;

            list-style-position: outside;

        }

    </style>

</head>

<body>

    <h1>Custom Unordered List</h1>

    <ul class=”custom-list”>

        <li>First item</li>

        <li>Second item</li>

        <li>Third item</li>

    </ul>

    <h1>Custom Ordered List</h1>

    <ol class=”custom-list”>

        <li>First item</li>

        <li>Second item</li>

        <li>Third item</li>

    </ol>

</body>

</html>

Explanation:

  • list-style-image: Uses an image as the bullet point.
  • list-style-type: Changes the bullet style (e.g., upper-roman, square, circle).
  • list-style-position:
    • inside: Bullets are inside the content flow.
    • outside: Bullets are outside the content flow (default).
  • Enhances the visual appearance of lists.

CSS Generated Content with ::after

Description:

This example demonstrates how to insert content after elements using the ::after pseudo-element.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>::after Pseudo-element Example</title>

    <style>

        .quote::after {

            content: ‘”’;

        }

        .quote::before {

            content: ‘“’;

        }

        .required::after {

            content: ‘*’;

            color: red;

            margin-left: 5px;

        }

    </style>

</head>

<body>

    <h1>Generated Content</h1>

    <p class=”quote”>This text is enclosed in quotation marks using ::before and ::after.</p>

    <label class=”required”>Username</label>

    <input type=”text” name=”username”>

</body>

</html>

Explanation:

  • ::before and ::after allow you to insert content before or after an element’s content.
  • content: Specifies the content to insert.
  • Can be used to add decorative elements or indicators (like the red asterisk for required fields).

CSS Variables in Media Queries

Description:

This example shows how to use CSS variables within media queries to adjust styles based on viewport size.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Variables in Media Queries Example</title>

    <style>

        :root {

            –main-color: blue;

        }

        body {

            background-color: var(–main-color);

        }

        @media (max-width: 600px) {

            :root {

                –main-color: green;

            }

        }

    </style>

</head>

<body>

    <h1>Variable Color Change</h1>

    <p>Resize the browser window to see the background color change.</p>

</body>

</html>

Explanation:

  • CSS variables can be redefined within media queries.
  • When the viewport is 600px wide or less, –main-color changes to green.
  • The background color of the body updates accordingly.

CSS Grid Auto-fill and Auto-fit

Description:

This example demonstrates how to create a responsive grid layout using auto-fill and auto-fit.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Grid Auto-fill and Auto-fit Example</title>

    <style>

        .grid {

            display: grid;

            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));

            grid-gap: 10px;

        }

        .item {

            background-color: lightblue;

            padding: 20px;

            text-align: center;

        }

    </style>

</head>

<body>

    <h1>Responsive Grid</h1>

    <div class=”grid”>

        <div class=”item”>1</div>

        <div class=”item”>2</div>

        <div class=”item”>3</div>

        <div class=”item”>4</div>

        <div class=”item”>5</div>

        <div class=”item”>6</div>

    </div>

</body>

</html>

Explanation:

  • grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));:
    • auto-fill: Fills the row with as many columns as fit.
    • minmax(150px, 1fr): Columns are at least 150px and grow to fill available space.
  • The grid adjusts the number of columns based on the viewport width.
  • Creates a responsive layout without media queries.

Responsive Typography with Viewport Units

Description:

This example shows how to create responsive text that scales with the viewport size using vw units.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Responsive Typography Example</title>

    <style>

        h1 {

            font-size: 5vw;

        }

        p {

            font-size: 2vw;

        }

    </style>

</head>

<body>

    <h1>Responsive Text</h1>

    <p>This text scales with the viewport width.</p>

</body>

</html>

Explanation:

  • 1vw: Equals 1% of the viewport width.
  • As the browser window resizes, the font size adjusts proportionally.
  • Useful for creating layouts that maintain proportions across devices.

CSS Masking

Description:

This example demonstrates how to use CSS masks to create interesting visual effects by masking an image with another image.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>CSS Masking Example</title>

    <style>

        .masked-image {

            width: 300px;

            height: 300px;

            background-image: url(‘background.jpg’);

            -webkit-mask-image: url(‘mask.png’);

            mask-image: url(‘mask.png’);

            -webkit-mask-size: cover;

            mask-size: cover;

        }

    </style>

</head>

<body>

    <h1>Masked Image</h1>

    <div class=”masked-image”></div>

</body>

</html>

Explanation:

  • mask-image: Defines an image to use as a mask layer.
  • The mask image determines which parts of the background image are visible.
  • mask-size: cover;: Scales the mask to cover the element.
  • Creates complex shapes and effects without modifying the original images.

CSS Responsive Tables

Description:

This example shows how to make tables responsive using CSS and media queries.

Code:

<!DOCTYPE html>

<html>

<head>

    <title>Responsive Table Example</title>

    <style>

        table {

            width: 100%;

            border-collapse: collapse;

        }

        th, td {

            border: 1px solid #ddd;

            padding: 8px;

        }

        /* Responsive layout */

        @media screen and (max-width: 600px) {

            table, thead, tbody, th, td, tr {

                display: block;

            }

            th {

                position: absolute;

                top: -9999px;

                left: -9999px;

            }

            td {

                border: none;

                position: relative;

                padding-left: 50%;

            }

            td::before {

                position: absolute;

                top: 8px;

                left: 8px;

                width: 45%;

                padding-right: 10px;

                white-space: nowrap;

                font-weight: bold;

            }

            td:nth-of-type(1)::before { content: “Name”; }

            td:nth-of-type(2)::before { content: “Age”; }

            td:nth-of-type(3)::before { content: “Email”; }

        }

    </style>

</head>

<body>

    <h1>Responsive Table</h1>

    <table>

        <thead>

            <tr>

                <th>Name</th><th>Age</th><th>Email</th>

            </tr>

        </thead>

        <tbody>

            <tr>

                <td>John Doe</td><td>30</td><td>john@example.com</td>

            </tr>

            <tr>

                <td>Jane Smith</td><td>25</td><td>jane@example.com</td>

            </tr>

        </tbody>

    </table>

</body>

</html>

Explanation:

  • On small screens, the table transforms into a block display.
  • Table headers are hidden, and data cells are displayed with ::before content that acts as labels.
  • Makes the table readable on devices with narrow screens.