Comprehensive CSS Study Notes

CSS Course Overview

  • Objective: This comprehensive course aims to teach CSS from the ground up, culminating in the development of a high-quality project.

  • CSS Purpose: CSS (Cascading Style Sheets) is responsible for adding style and aesthetics to websites.

  • Course Structure:

    • Levels: Five progressive levels covering basic to advanced CSS concepts.

    • Practice: Each level includes practice questions to reinforce learning.

    • Project: A full-scale Amazon.in clone project will be built using all learned concepts.

  • Target Audience: Students with no prior CSS knowledge, starting from a zero level.

  • Learning Outcomes: Gain strong CSS fundamentals, practical application skills, and the ability to build website clones.

  • Resources: All course notes are available in the description box.

Code Editor: Visual Studio Code (VS Code)

  • Necessity: To write any program or code, a code editor is essential.

  • Choice: Visual Studio Code (VS Code) is recommended for this course.

  • Analogy: Code editors are like notebooks for writing code, but they offer significant external functionalities and resources.

  • Benefits of VS Code:

    • Provides a seamless and efficient environment for coding.

    • Prepares students for future project development (e.g., websites, software systems).

    • Freely available from Microsoft.

  • Installation Guide:

    1. Search: Go to Google and search for "Download VS Code."

    2. Website: Click on the first link (code.visualstudio.com/download).

    3. Platform Selection: Choose the appropriate installer for your operating system (Windows, macOS, Linux).

      • Windows: Most users have a 64-bit system; click to download. If unsure, download the user installer.

      • macOS: Download the .zip file.

    4. Installation Process:

      • Windows: Run the installer, accept the license agreement, click "Next" through the prompts, and tick the option to "Add 'Open with Code' action to Windows Explorer context menu."

      • macOS: Drag the VS Code app to the Applications folder.

    5. Completion: Once ticked (Windows) or moved (macOS), VS Code will be fully installed and ready for first use.

  • Initial Setup in VS Code:

    1. Open VS Code: The interface will show options like "Start New File" (if newly installed) or "Recent" files.

    2. Create a Folder: On your desktop (or preferred location), create a new folder named "Classroom" (or any name you prefer) to store all your code.

    3. Open Folder in VS Code:

      • Go to File > Open Folder.

      • Navigate to and select the "Classroom" folder.

      • Click "Open."

    4. Welcome Screen: Close the "Welcome" tab.

    5. Create New File:

      • Click the "New File" icon (first icon on the left panel, within the classroom folder).

      • Name the file index.html.

      • Reason for HTML: CSS styles an HTML document. You need a "house" (HTML) before you can "paint" it (CSS). HTML elements are necessary to apply CSS styles to.

    6. Verify File Creation: Double-click the index.html file in your "Classroom" folder to open it in a browser (e.g., Chrome). It will appear as a blank web page.

    7. Optional: You can create subfolders within "Classroom" using the "New Folder" icon (second icon).

    8. Naming Convention: For beginners, consistently naming the main HTML file index.html is recommended to minimize errors.

Web Development Fundamentals: HTML, CSS, JavaScript Overview

  • Three Core Technologies: Web development beginners typically learn three languages:

    1. HTML (HyperText Markup Language):

      • Purpose: Builds the basic structure or layout of a web page/website.

      • Analogy: Like laying bricks, building walls, and putting up a roof for a house (the basic structure).

      • Prior Learning: Covered in detail in a 2-hour one-shot lecture with notes.

      • Ease of Learning: Relatively easy to learn for beginners.

    2. CSS (Cascading Style Sheets):

      • Purpose: Adds style, beauty, and formatting to the basic HTML structure.

      • Analogy: Deciding paint colors, sofa colors, lamp sizes, and lighting for a house to match the overall aesthetic.

      • Focus of this Lecture: Styling, beauty, makeup, paint, colors, text formatting.

    3. JavaScript:

      • Purpose: Adds logic and interactivity to a website (how things work).

      • Analogy: Implementing switches to turn lights on/off, or a regulator to control fan speed.

      • Future Topic: Will be covered in a subsequent web development lecture.

The Importance of CSS: Visual Impact and User Psychology

  • Aesthetic Appeal: CSS makes websites visually appealing, which is crucial for user experience.

  • Premium Feel: Well-designed websites (modern fonts, good pictures/animations, complementary colors, sufficient whitespace, good font styles) create a premium perception.

  • Human Psychology: This aesthetic appeal can subconsciously influence users to spend more or perceive products as more valuable.

  • Brand Strategy Examples:

    • Food Brands (e.g., Coca-Cola, McDonald's, Zomato): Often use red and yellow mixtures.

      • Red: Associated with passion, happiness, and can stimulate appetite.

    • Banking/Fintech Brands (e.g., Razorpay, Paytm, PhonePe, Google Pay): Frequently use blue.

      • Blue: Conveys stability and security, reassuring users who are handling their money through these platforms.

  • Comprehensive Styling: CSS controls everything from subtle color choices to major layout decisions (element alignment, button placement, size, background color, font style).

  • Conclusion: CSS is a highly important entity in front-end development and should be treated as such.

Level 1: Basics of CSS

What is CSS?

  • Full Form: Cascading Style Sheets.

  • Nature: Not a programming language (like C++, Java, Python) that involves if-else statements, variables, or loops. It is a styling language.

  • Purpose: Primarily used to add style to web pages.

  • Definition: "A language that is used to describe the style of an HTML document."

  • Prerequisite: HTML content must exist before CSS can be applied (you need walls before you can paint them).

Illustrating CSS Impact: The Netflix Example

  • Scenario: Opening Netflix on a browser and then using the developer tools (Inspect option) to delete the <head> section of the HTML document (which typically contains CSS links).

  • Observation: Without CSS, the Netflix website appears broken and unstyled.

    • Text becomes tiny or disproportionately large.

    • Images are badly sized.

    • Buttons lose their styling (e.g., a gray, unclickable button).

    • Overall layout is chaotic and "broken-up."

  • Conclusion: CSS makes a monumental difference, transforming a functional but unattractive HTML structure into a beautiful, user-friendly website.

CSS Syntax

  • Basic Structure: Consists of a selector, followed by curly braces containing property-value pairs.
    css selector { property: value; }

  • Selector:

    • Purpose: Selects which HTML tag(s) the style should apply to.

    • Example: If you write <p> text in HTML and want to style it, you'd use p as the selector.

  • Curly Braces ({}): Enclose the declaration block (all property-value pairs for the selected element).

  • Property-Value Pair:

    • Property: The specific aspect of the element you want to style (e.g., color, font-size, background-color).

    • Value: The desired setting for that property (e.g., red for color, 20px for font-size).

    • Colon (:): Separates the property from its value.

    • Semicolon (;): Terminates each property-value pair. Although sometimes optional for a single pair, it's a good programming practice to always include it and indicates and experienced developer.

  • Example with h1:

    • HTML: <h1 id="main-heading">Hello from Apna College</h1>

    • CSS:
      css h1 { color: red; }

    • VS Code Emmet (for HTML):

      • Type ! then Enter for a basic HTML boilerplate.

      • Type h1 then Enter for an h1 tag.

Memorization vs. Understanding in CSS

  • Key Principle: In development, very few things need to be memorized; most are learned through practice or looked up.

  • Memorize Syntax: Focus on remembering selector { property: value; }.

  • Understand Concepts: Concentrate on comprehending what each property does and how it interacts with elements.

  • Google for Properties: It is common and acceptable to search for specific CSS properties when needed.

Ways to Add CSS (Styling)

  • There are three main ways to include CSS in an HTML document:

    1. Inline Styling:

      • Method: Add CSS directly within the HTML tag using the style attribute.

      • Syntax: <tag style="property: value; property2: value2;">Content</tag>

      • Example: <h1 style="color: red;">Hello from Apna College</h1>

      • Pros: Quick for small, isolated style changes.

      • Cons: Not scalable, mixes HTML and CSS, difficult to maintain for large projects, generally considered bad practice.

    2. Internal Styling (Using <style> Tag):

      • Method: Place CSS rules within <style> tags in the <head> section of the HTML document.

      • Syntax:
        html <head> <style> selector { property: value; } </style> </head>

      • Example:
        html <head> <style> h1 { color: red; } </style> </head> <body> <h1>Hello from Apna College</h1> </body>

      • Pros: Good for single-page styles, centralizes styles for that page.

      • Cons: Not suitable for multi-page websites, can make HTML file large and harder to read.

    3. External Styling (Using External Style Sheet):

      • Method: Create a separate .css file (e.g., style.css) and link it to the HTML document using the <link> tag in the <head> section.

      • CSS File (style.css):
        css h1 { color: red; }

      • HTML File (index.html):
        html <head> <link rel="stylesheet" href="style.css"> </head> <body> <h1>Hello from Apna College</h1> </body>

      • <link> Tag Attributes:

        • rel="stylesheet": Specifies the relationship of the linked document (it's a stylesheet).

        • href="style.css": Specifies the path to the CSS file. If the CSS file is in a different folder, the full path is required.

      • Pros (and industry standard):

        • Separates concerns (HTML for structure, CSS for style).

        • Highly maintainable and scalable for large projects.

        • Cacheable by browsers, leading to faster loading times after the first visit.

        • Promotes code reusability across multiple HTML pages.

      • Recommendation: This is the most professional and preferred method for adding CSS.

CSS Priority (Cascading Order)

  • Rule: When conflicting styles are applied to the same element, CSS follows specific rules to determine which style takes precedence.

  • General Principle: Styles applied later or more specifically (closer to the element) tend to have higher priority.

  • Example:

    • External CSS sets h1 { color: green; }.

    • Inline CSS sets <h1 style="color: red;">...</h1>.

    • Result: The h1 will appear red due to inline styling's higher priority.

  • Order of Precedence (from lowest to highest):

    1. Browser's default styles.

    2. External stylesheets.

    3. Internal stylesheets (<style> tag).

    4. Inline styles (style attribute).

  • Best Practice: To avoid confusion and ensure maintainable code, try to use external stylesheets primarily and avoid changing the same style with multiple methods unless absolutely necessary.

color Property

  • Purpose: Sets the foreground color of an element.

  • Foreground Color: Refers to the color of content that is directly visible on top of background elements.

    • Examples: Text, button labels, link text.

  • Syntax: color: value;

  • Value Types:

    • Predefined Color Names: Over 100 fixed names (e.g., red, blue, green, pink, black, white, gray, brown, teal, turquoise, tomato, sky blue, slate gray, sea green, purple).

    • VS Code Helper: VS Code provides a color picker and auto-suggestions for color names.

  • Example Usage:

    • HTML:
      html ¨K106K ¨K107K <button>Click Me</button>

    • CSS (style.css):
      css h1 { color: green; } p { color: purple; } button { color: brown; }

background-color Property

  • Purpose: Sets the background color of an element.

  • Syntax: background-color: value;

  • Value Types: Same as color property (predefined names, color systems - see next section).

  • Default: The default background color for the overall web page (body) is usually white.

  • Example Usage:

    • HTML: (Same as above, plus the <body> tag)

    • CSS (style.css):
      css body { background-color: black; /* Sets the entire page background to black */ } button { color: brown; background-color: green; /* Sets the button's background to green */ }

  • Combining Properties: Multiple CSS properties for the same selector can be declared within a single block.
    css button { color: brown; background-color: green; }

  • Design Considerations/Self-Expectations:

    • Beginner Stage: It's okay if your initial CSS designs are not aesthetically perfect or look "old-fashioned." The focus is on learning properties.

    • Professional Workflow: In companies, UI/UX designers create a detailed design (e.g., using Figma) which is then handed to a front-end developer to implement. The developer's role is to translate the design into code, not necessarily to be a designer themselves.

    • Improving Design Skills: While not a designer, understanding basic design principles (color theory, complementary colors, white space, typography) can significantly improve the appearance of your web pages. Tools like color palettes (e.g., Coolors.co or Canva) can help find harmonious color combinations.

Color Systems

  • Purpose: To define colors that don't have predefined names or to achieve specific shades.

  • Primary Focus: RGB and Hex color systems are the most frequently used.

    1. RGB (Red, Green, Blue) System:

      • Foundation: Based on the three primary colors of light: Red, Green, Blue. All other colors are mixtures of these.

        • Red + Green = Yellow

        • Red + Blue = Magenta/Violet

        • Blue + Green = Cyan

        • Red + Green + Blue (in equal, full quantities) = White

      • Syntax: rgb(red_value, green_value, blue_value);

      • Value Range: Each color component (red, green, blue) can be an integer from 00 to 255255.

        • 00: No intensity of that color.

        • 255255: Full intensity of that color.

      • Examples:

        • rgb(255, 0, 0); = Red (full red, no green, no blue)

        • rgb(0, 255, 0); = Green (no red, full green, no blue)

        • rgb(255, 255, 0); = Yellow (full red, full green, no blue)

      • Shades: Varying the values (e.g., rgb(200, 255, 0); for a greener yellow) creates different shades.

      • Practical Use: You don't need to memorize RGB values. VS Code's color picker helps, or you can use online color pickers/generators (e.g., Coolors.co) which often display RGB values.

    2. Hexadecimal (Hex) System:

      • Purpose: A shorter, alternative way to represent RGB colors using hexadecimal numbers.

      • Hexadecimal Basics (Extra Knowledge):

        • Decimal: Base-10 system (0-9 digits).

        • Binary: Base-2 system (0, 1 digits).

        • Hexadecimal: Base-16 system (0-9 and A-F digits).

          • A = 1010, B = 1111, …, F = 1515.

      • Syntax: #RRGGBB

        • ##: Two hexadecimal digits represent the intensity of Red (00 to FF).

        • GG: Two hexadecimal digits for Green (00 to FF).

        • BB: Two hexadecimal digits for Blue (00 to FF).

        • 00 in Hex = 00 in Decimal.

        • FF in Hex = 255255 in Decimal.

      • Examples:

        • #FF0000; = Red (full red, no green, no blue)

        • #00FF00; = Green (no red, full green, no blue)

        • #FFFF00; = Yellow (full red, full green, no blue)

      • Prefix: Always use a # (hash) symbol before hexadecimal color codes.

      • Practical Use: Like RGB, you don't need to memorize hex codes. Use VS Code's color picker or online tools.

      • Color Palettes: Websites like Coolors.co provide pre-generated color palettes with their respective hex codes, which are useful for ensuring complementary and aesthetically pleasing designs.

CSS Selectors

  • Purpose: Specify which HTML elements a CSS rule should apply to.

  • Types of Selectors:

    1. Universal Selector (*):

      • Syntax: * { property: value; }

      • Purpose: Selects all elements on the HTML document.

      • Analogy: If you want every item in your notebook to be pink, you'd use the universal selector to apply pink color to all.

      • Example: ```css

        • {
          color: blue; /* Sets all text on the page to blue */
          }
          ```

      • Note: Usually used for global styles like resetting margins/padding or setting a default font.

    2. Element Selector (Type Selector):

      • Syntax: tagname { property: value; } (e.g., p, h1, div)

      • Purpose: Selects all instances of a specific HTML tag.

      • Example:
        css h1 { color: green; /* Sets all h1 headings to green */ }

      • Specificity (Priority): If a universal selector sets color to blue, and an element selector sets h1 color to green, the h1 elements will be green because the element selector is more specific.

      • CSS Cascading: Rules written later in the stylesheet typically override earlier rules if they target the same element.

    3. ID Selector (#):

      • Syntax (HTML): <tag id="unique-id">Content</tag> (e.g., <h1 id="heading1">...</h1>)

      • Syntax (CSS): #unique-id { property: value; } (e.g., #heading1 { color: yellow; })

      • Purpose: Selects a single, unique HTML element that has the specified id attribute.

      • Uniqueness: An id should be unique within a single HTML document. Applying the same id to multiple elements is considered bad programming practice.

    4. Class Selector (.):

      • Syntax (HTML): <tag class="class-name">Content</tag> (e.g., <p class="my-class">...</p>)

      • Syntax (CSS): .class-name { property: value; } (e.g., .my-class { color: magenta; })

      • Purpose: Selects all HTML elements that have the specified class attribute, allowing the same style to be applied to multiple elements.

      • Analogy: Like students in a class, multiple elements can belong to the same "class" and share its styles.

  • Combining Selectors (Comma Separator):

    • Syntax: selector1, selector2, selector3 { property: value; }

    • Purpose: Apply the same style to multiple different elements simultaneously.

    • Example:
      css h1, h2, h3 { color: red; /* Sets all h1, h2, and h3 headings to red */ }

Practice Set 1

Question 1: Create a simple div with ID box, add some text content, and set its background color to blue.
  • HTML:
    html ¨K128K ¨K130K ¨K131K ¨K129K

  • CSS:
    css #box { background-color: blue; color: white; /* Optional: for better visibility */ } /* CSS Comments: In VS Code, select lines and press Ctrl + / (Windows) or Cmd + / (Mac) */ /* Manual CSS Comment: / * This is a comment * / */

Question 2: Create three headings (h1, h2, h3), give them all a class heading, and set their color to red.
  • HTML:
    html ¨K132K ¨K133K ¨K134K

  • CSS (using class selector):
    css .heading { color: red; }

  • CSS (alternative using combined element selectors):
    css h1, h2, h3 { color: red; }

Question 3: Create a button and set its background color to green using style.css, then to blue using an internal <style> tag, and finally to pink using inline style attribute.
  • HTML (initial):
    html <button>Click Me</button>

  • CSS (style.css - first step):
    css button { background-color: green; }

  • HTML (with internal style - second step):
    html <head> <style> button { background-color: blue; } </style> <link rel="stylesheet" href="style.css"> </head> <body> <button>Click Me</button> </body>

  • HTML (with inline style - final step):
    html <head> <style> button { background-color: blue; } </style> <link rel="stylesheet" href="style.css"> </head> <body> <button style="background-color: pink;">Click Me</button> </body>

  • Result & Priority: The button will be pink. Inline style has the highest priority. If no inline style, the <style> tag's rule will apply (blue) as it's typically processed after the link tag in the head. If no <style> tag, style.css's rule will apply (green). This highlights the importance of using a single, consistent method for styling (like style.css) to prevent conflicts.

Level 2: Box Model in CSS

The Box Model Concept

  • Core Idea: In CSS, every HTML element (whether it's an image, div, span, heading, paragraph, button, etc.) is fundamentally treated as a rectangular box.

  • Visualization: Using browser developer tools (Inspect Element), hovering over any element reveals these rectangular boxes.

    • Blue Area (Chrome default): Represents the element's actual content area.

    • Orange Area (Chrome default): Represents the element's margin.

  • Components of the Box Model: The box model consists of five key parts:

    1. Content: The actual text, images, or other media within the element.

      • Height: Vertical space occupied by the content.

      • Width: Horizontal space occupied by the content.

    2. Padding: The space between the element's content and its border. It adds internal spacing.

    3. Border: The edge or boundary around the element's padding and content.

    4. Margin: The space outside the element's border, separating it from other elements. It adds external spacing.

HTML & CSS Setup for Level 2

  • HTML (index.html):
    html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS Level 2</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>Heading</h1> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p> <button>Click Me</button> <div>This is a Div</div> </body> </html>

  • CSS (style.css): (Initially empty)

height Property

  • Purpose: Sets the vertical height of an element's content area.

  • Syntax: height: value;

  • Units: Primarily pixels (px) for absolute units (e.g., 50px, 100px). Other units like cm, in, mm are available but less common.

  • Default Behavior: By default, a div's height is equal to the height of its content.

  • Visualization: Best seen by assigning a background-color to the div.

  • Example:
    css div { background-color: pink; height: 100px; /* Initially 100px */ } /* In browser inspect, you can temporarily change height to 200px, 500px to see effect */

width Property

  • Purpose: Sets the horizontal width of an element's content area.

  • Syntax: width: value;

  • Units: Primarily pixels (px).

  • Default Behavior:

    • Block-level elements (e.g., div, h1, p): By default, they occupy 100% of the available width of their parent container (often the full browser width).

    • Inline elements (e.g., span, button, input, a): By default, they only occupy the width necessary for their content.

  • Example:
    css div { background-color: pink; height: 100px; width: 200px; /* Limits div width to 200px */ } h1 { background-color: aquamarine; width: 200px; height: 50px; text-align: center; /* Text aligns within the h1's 200px width */ }

  • Important Note on text-align: text-align aligns content within its parent element or itself, not necessarily the entire document. If an h1 has a width of 200px and text-align: center;, its text will center within those 200px, not the entire page.

border Property

  • Purpose: Creates a boundary around an element's content and padding.

  • Individual Properties (Long-form):

    1. border-width: Sets the thickness of the border.

      • Syntax: border-width: value;

      • Units: Pixels (e.g., 2px, 5px, 10px).

    2. border-style: Sets the visual style of the border.

      • Syntax: border-style: value;

      • Common Values: solid, dashed, dotted, double, none.

      • MDN Resource: Explore text-decoration-style properties on MDN for more options.

    3. border-color: Sets the color of the border.

      • Syntax: border-color: value;

      • Default: If not specified, the border color defaults to the color property of the element (often black for text).

  • Example:
    css div { /* ... other properties ... */ border-width: 2px; border-style: solid; border-color: brown; } /* Experiment with different styles: dashed, dotted, double */

border Shorthand Property

  • Purpose: A concise way to set border-width, border-style, and border-color in a single declaration.

  • Syntax: border: [width] [style] [color];

  • Order: The order of width, style, and color generally doesn't matter, but this is the common convention.

  • Example:
    css div { /* ... other properties ... */ border: 2px solid brown; /* Shorthand for width, style, color */ } /* Comment out individual border properties when using shorthand */

border-radius Property

  • Purpose: Rounds the corners (edges) of an element's border, making them less pointed.

  • Syntax: border-radius: value;

  • Value Types:

    1. Pixels (px): Directly specifies the radius in pixels.

      • Larger value = more rounded corners.

      • Small value = slightly rounded corners.

      • Example: border-radius: 15px;

    2. Percentage (%): Specifies the radius as a percentage of the element's width/height.

      • Creating a Circle: If an element is a perfect square (height == width), border-radius: 50%; will turn it into a circle.

      • Example:
        css div { height: 100px; width: 100px; border: 2px solid black; background-color: pink; border-radius: 50%; /* Makes it a circle */ }

  • Individual Corner Control: You can also set border-top-left-radius, border-top-right-radius, border-bottom-left-radius, border-bottom-right-radius for specific corners.

padding Property

  • Purpose: Adds space inside an element, between its content and its border.

  • Syntax: padding: value; or padding-[direction]: value;

  • Units: Pixels (px) or other units.

  • Individual Direction Properties:

    • padding-top: value;

    • padding-right: value;

    • padding-bottom: value;

    • padding-left: value;

  • Visualization (Chrome Inspect): Padding is typically highlighted in green.

  • Impact: Increases the overall size of the element (unless box-sizing: border-box; is used, which includes padding within the specified width/height).

  • Shorthand for padding:

    1. Single Value: padding: 25px; (Applies 25px padding to all four sides: top, right, bottom, left).

    2. Four Values (Clockwise): padding: [top] [right] [bottom] [left];

      • Example: padding: 1px 2px 3px 4px; (Top 1px, Right 2px, Bottom 3px, Left 4px).

margin Property

  • Purpose: Adds space outside an element, between its border and neighboring elements.

  • Syntax: margin: value; or margin-[direction]: value;

  • Units: Pixels (px) or other units.

  • Individual Direction Properties:

    • margin-top: value;

    • margin-right: value;

    • margin-bottom: value;

    • margin-left: value;

  • Visualization (Chrome Inspect): Margin is typically highlighted in orange.

  • Impact: Creates separation between elements.

  • Default Margins: Some elements (e.g., div, h1, p) have default margins applied by browsers.

  • Block-level Element Default: A div (block-level element) by default extends to 100% width, so any remaining horizontal space to its right is automatically considered margin.

  • Shorthand for margin: Same as padding shorthand.

    1. Single Value: margin: 25px; (Applies 25px margin to all four sides).

    2. Four Values (Clockwise): margin: [top] [right] [bottom] [left];

      • Example: margin: 1px 2px 3px 4px;

Practice Set 3

Question 1: Create a div with height/width of 100px, background color green, and border-radius: 50%.
  • HTML:
    html ¨K152K

  • CSS:
    css div { height: 100px; width: 100px; background-color: green; border-radius: 50%; }

  • Homework Problem (Traffic Light): Create a rectangular box containing three circles (red, yellow, green) stacked vertically to resemble a traffic light. (This requires concepts learned throughout Level 2).

Question 2: Create a web page layout with a header, a footer, and a content area. The content area should have three divs with height/width 100px and unique background colors/opacity 0.5. Add a 2px solid black border to all divs. Integrate the previous navbar into the header. Give the content area an appropriate height.
  • HTML Structure (using semantic tags):
    ```html

    Div 1

    Div 2

    Div 3

    ```

  • CSS for content-box:

    .content-box {
        height: 100px;
        width: 100px;
        border: 2px solid black;
    }
    /* Apply individual background colors with RGBA for opacity */
    .content-box:nth-child(1) { /* :nth-child(n) is a pseudo-class for selecting child elements */
        background-color: rgba(255, 0, 0, 0.5); /* Red with 50% opacity */
    }
    .content-box:nth-child(2) {
        background-color: rgba(0, 255, 0, 0.5); /* Green with 50% opacity */
    }
    .content-box:nth-child(3) {
        background-color: rgba(0, 0, 255, 0.5); /* Blue with 50% opacity */
    }
    
    /* Bring divs to same line and center them (optional, if desired for the solution) */
    #content {
        display: flex;
        justify-content: space-around; /* Or space-evenly, center */
        align-items: center;
        height: 720px; /* Example height to push footer to bottom */
    }
    footer {
        background-color: #222; /* Example dark color */
        color: white;
        text-align: center;
        padding: 20px 0;
    }
    

Level 3: CSS Units & Position Property

Units in CSS

  • Purpose: Define the size or dimension of elements.

  • Types of Units:

    1. Absolute Units:

      • Characteristic: Fixed values that don't change based on other elements or viewport size.

      • Examples: px (pixels), cm (centimeters), mm (millimeters), in (inches).

      • Most Common: px is the most frequently used absolute unit in web development.

    2. Relative Units:

      • Characteristic: Values that are relative to (change based on) another element's size, the viewport size, or the root font size.

      • Most Common: %, em, rem, vw, vh.

  • Understanding Relative Units:

    • % (Percentage):

      • Purpose: Defines size as a percentage relative to the parent element's size for a specific property.

      • Example: If a child div has width: 50%; and its parent div has width: 200px;, the child's width will be 100px (50% of 200px).

      • Practical Use: Useful for creating flexible layouts where elements scale with their container.

    • em (Em):

      • Text Properties (e.g., font-size): 1em is relative to the font-size of the parent element.

        • Example: Child font-size: 2em; means twice the parent's font size.

      • Other Properties (e.g., width): 1em is relative to the font-size of the element itself.

        • Example: If an element has font-size: 20px; and width: 5em;, its width will be 100px (5 * 20px).

      • Key Distinction: Crucial to remember whether em references the parent's font size or the element's own font size, as this behavior varies by property.

    • rem (Root Em):

      • Purpose: 1rem is always relative to the font-size of the root HTML element (the <html> tag).

      • Default Root Font Size: Most browsers set the default font-size of the <html> element to 16px. So, 1rem usually equals 16px unless explicitly changed.

      • Example: Child width: 5rem; on an element where the root font size is 16px would result in a width of 80px (5 * 16px).

      • Benefit: Provides consistent scaling across the entire document, regardless of parent element font sizes, making responsiveness easier to manage.

    • vw (Viewport Width):

      • Purpose: 1vw is equal to 1% of the viewport's width (the visible browser window width).

      • Example: width: 50vw; means the element will take up 50% of the browser window's width.

    • vh (Viewport Height):

      • Purpose: 1vh is equal to 1% of the viewport's height (the visible browser window height).

      • Example: height: 100vh; means the element will take up 100% of the browser window's height.

  • Practical Use: Relative units are essential for creating responsive web designs that adapt well to different screen sizes.

Position Property

  • Purpose: Controls how an element is positioned within its containing document or parent element.

  • Default Positioning: All HTML elements, by default, have position: static;.

  • Key Properties for Positioning:

    • top: Sets the distance from the top edge.

    • right: Sets the distance from the right edge.

    • bottom: Sets the distance from the bottom edge.

    • left: Sets the distance from the left edge.

    • z-index: Controls the stacking order of overlapping elements (which element appears on top).

  • Possible Values for position:

    1. static (Default):

      • Behavior: Elements are positioned according to the normal flow of the document (where they naturally appear in the HTML).

      • top, right, bottom, left, z-index: These properties have no effect on statically positioned elements.

    2. relative:

      • Behavior: The element is positioned relative to its normal position. It occupies space in the document flow as usual.

      • top, right, bottom, left: These properties shift the element from its original position while still maintaining its original space in the document flow. (e.g., top: 10px; moves it 10px down from its original top position).

      • z-index: Now works, controlling stacking order if it overlaps other elements.

      • Overlap: Relative positioning can cause elements to overlap others.

    3. absolute:

      • Behavior: The element is positioned relative to its closest positioned ancestor (a parent element with position: relative, absolute, fixed, or sticky). If no positioned ancestor exists, it's positioned relative to the initial containing block (usually the <html> or <body> element, which defaults to the browser window).

      • Document Flow: An absolutely positioned element is removed from the normal document flow. Other elements will behave as if it's not there, potentially moving into its original space.

      • top, right, bottom, left: Positions the element precisely based on these offsets from its positioned ancestor's edges.

      • z-index: Works to control stacking order.

    4. fixed:

      • Behavior: The element is positioned relative to the browser viewport (the visible window) and stays in that position even when the page is scrolled.

      • Document Flow: Removed from the normal document flow.

      • top, right, bottom, left: Positions the element precisely based on these offsets from the viewport edges.

      • Common Use: For elements that should always be visible, like sticky navigation bars (headers) or footers.

    5. sticky: (Lesser Used, Modern CSS)

      • Behavior: A hybrid: it's positioned relative until a certain scroll position is met, at which point it becomes fixed.

      • Syntax: position: sticky; top: 0; (The element will stick to the top of the viewport when it reaches that position during scroll).

      • Common Use: For navigation elements or sidebars that become fixed after a user scrolls past a certain point.

z-index Property

  • Purpose: Controls the vertical stacking order of positioned elements that overlap. Elements with a higher z-index value appear on top of elements with a lower z-index value.

  • Context: Only applies to elements that have a position value other than static (i.e., relative, absolute, fixed, or sticky).

  • Default: The default z-index for all elements is 0.

  • Behavior:

    • Positive Values: Elements with z-index: 1, z-index: 2, etc., will appear on top of elements with lower z-index values.

    • Negative Values: Elements with z-index: -1, z-index: -2, etc., will appear beneath elements with z-index: 0 (or positive values).

    • Default Overlap (if z-index is same or not set): Elements appearing later in the HTML document flow (index.html) will typically appear on top of earlier elements.

  • Analogy (from 3D Space): The z-index concept comes from the z-axis in 3D coordinate systems, which represents depth or distance from the viewer. A higher z-index means closer to the viewer.

Setting a Background Image

  • Purpose: To place an image as the background of an element.

  • Website Resource: Unsplash.com is a popular website for free, high-quality, copyright-free images.

  • Steps to Add a Background Image to a div:

    1. Download Image: Find and download an image (e.g., from Unsplash).

    2. Save Image: Place the image file (e.g., cat_photo.jpg) in the same folder as your index.html and style.css for simplicity.

    3. CSS Property: Use background-image.

      • Syntax: background-image: url('path/to/image.jpg');

      • Example:
        css div { height: 200px; width: 200px; background-image: url('cat_photo.jpg'); }

    4. Important: The element needs a defined height and width for the background image to be visible.

  • Common Issue: Background images often appear pixelated, stretched, or repeated, especially if the image dimensions don't match the element dimensions.

background-size Property

  • Purpose: Controls how the background image is sized and positioned within its element.

  • Syntax: background-size: value;

  • Key Values:

    1. cover:

      • Behavior: Scales the background image to be as large as possible so that it completely covers the background area of the element. If the image aspect ratio differs from the element, it will be cropped to fit.

      • Result: No empty space, but parts of the image might be cut off.

      • Most Common Use: Often preferred for full-width or full-height sections where you want the image to always fill the available space.

      • Example: background-size: cover;

    2. contain:

      • Behavior: Scales the background image to the largest size possible without cropping or stretching the image. The entire image will be visible.

      • Result: The image fits entirely within the element, but there might be empty space (which will be filled by the background-color or background-repeat).

      • Handling Empty Space: To prevent repetition of the image in the empty space, use background-repeat: no-repeat;.

      • Example: background-size: contain; background-repeat: no-repeat;

    3. auto (Default):

      • Behavior: The background image retains its original dimensions.

      • Result: Can lead to images being too large, too small, or repeated.

  • Recommendation: background-size: cover; is generally preferred for a clean, full-coverage look.

Practice Set 5

Question 1: Create the following layout using given HTML: A paragraph, a div with ID nature-div and text "Love Nature", and another paragraph. Use Emmet lorem*5 for paragraph text.
  • HTML:
    html ¨K185K ¨K186K ¨K184K ¨K187K ¨K188K

  • CSS for the div (#nature-div):
    css #nature-div { height: 200px; /* Example height */ width: 200px; /* Example width */ background-image: url('nature.jpg'); /* Assuming 'nature.jpg' is in the same folder */ background-size: cover; /* To make the image fit well */ color: white; /* For text visibility */ text-align: center; /* To center the text */ line-height: 200px; /* To vertically center text if it's single line */ }

Question 2: Use the appropriate position property to place the div from Question 1 on the right side of the page. The div should not move even on scroll.
  • CSS for the div (#nature-div):
    css #nature-div { /* ... (previous styles) ... */ position: fixed; /* Ensures it doesn't move on scroll */ top: 250px; /* Adjust top position as needed */ right: 0; /* Places it on the extreme right */ }

  • Explanation:

    • position: fixed; is chosen because the element needs to stay in a fixed position relative to the viewport, even during scrolling.

    • top: 250px; (or any value) positions it vertically from the top of the viewport.

    • right: 0; positions it flush with the right edge of the viewport.

  • Note: Adding sufficient text to the paragraphs in HTML is important to make the page scrollable and demonstrate the fixed property.

Level 4: Flexbox in CSS

Introduction to Flexbox

  • Purpose: Flexbox (Flexible Box Layout) is a one-dimensional layout CSS module that provides an efficient way to layout, align, and distribute space among items in a container, even when their size is unknown or dynamic.

  • Complexity: Can initially seem complicated due to many properties, but it becomes intuitive with practice.

  • Core Idea: Arranging items in a single row (horizontally) or a single column (vertically) within a container.

  • Analogy: Imagine a container (an outer div or nav bar) with several items inside (buttons, links, other divs). Flexbox helps arrange these items neatly.

  • Flex Model Components:

    1. Flex Container: The parent element to which display: flex; is applied. This enables flex context for all its direct children.

    2. Flex Items: The direct children of the flex container.

    3. Main Axis: The primary axis along which flex items are laid out. By default, it's horizontal (left to right for row direction).

    4. Cross Axis: The axis perpendicular to the main axis. By default, it's vertical (top to bottom for row direction).

    • Axis Orientation: The main and cross axes can change based on the flex-direction property.

HTML & CSS Setup for Level 4 (Flexbox Playground)

  • HTML (index.html):
    html ¨K193K ¨K192K

  • CSS (style.css): (Initial setup, may vary slightly)
    css h1 { text-align: center; } #container { height: 500px; width: 800px; background-color: lightgray; border: 2px solid black; margin: 20px auto; /* Centers the container horizontally */ display: flex; /* Makes it a flex container */ /* ... other flex properties will be added here ... */ } #container div { height: 100px; width: 100px; border: 1px solid gray; text-align: center; line-height: 100px; /* Vertically centers text in a single line */ /* Individual background colors for demonstration */ } /* Individual background colors for box1 to box5 */ #box1 { background-color: red; } #box2 { background-color: blue; } #box3 { background-color: green; } #box4 { background-color: yellow; } #box5 { background-color: orange; }

  • Enabling Flexbox: display: flex; on the container element (#container).

    • Applying display: flex; automatically arranges flex items in a row by default. All items will try to fit on one line, and their default width/height behavior changes to accommodate this.

flex-direction Property (Container Property)

  • Purpose: Establishes the main axis, thus defining the direction flex items are placed in the flex container.

  • Syntax: flex-direction: value;

  • Values:

    1. row (Default):

      • Main Axis: Horizontal, runs from left to right.

      • Cross Axis: Vertical, runs from top to bottom.

      • Result: Flex items are arranged side-by-side from left to right.

    2. row-reverse:

      • Main Axis: Horizontal, runs from right to left.

      • Result: Flex items are arranged side-by-side from right to left (the order of items is reversed visually, but not in the HTML source).

    3. column:

      • Main Axis: Vertical, runs from top to bottom.

      • Cross Axis: Horizontal, runs from left to right.

      • Result: Flex items are stacked vertically from top to bottom.

      • Note: Items will try to shrink vertically to fit the container's height if flex-wrap is not used.

    4. column-reverse:

      • Main Axis: Vertical, runs from bottom to top.

      • Result: Flex items are stacked vertically from bottom to top.

  • Key Behavior: Flex items will attempt to fit within their container. If they are in row direction and their combined width exceeds the container's width, they will overflow unless flex-wrap is used. Similarly for column and height.

justify-content Property (Container Property)

  • Purpose: Aligns flex items along the main axis of the flex container.

  • Syntax: justify-content: value;

  • Common Values (assuming flex-direction: row;):

    1. flex-start (Default): Items are packed towards the start of the main axis (left).

    2. flex-end: Items are packed towards the end of the main axis (right).

    3. center: Items are centered along the main axis.

    4. space-between: Items are evenly distributed in the line; first item is at the start line, last item at the end line. (No space at container edges).

    5. space-around: Items are evenly distributed in the line with equal space around them. Note: The space between items is double the space at the edges.

    6. space-evenly: Items are distributed so that the spacing between any two adjacent items, and the space before the first item and after the last item, is equal.

  • Example (with flex-direction: row;):
    css #container { display: flex; flex-direction: row; justify-content: center; /* Centers items horizontally */ }

  • Behavior with column: If flex-direction: column;, justify-content will align items vertically (along the column).

    • flex-start: Items at the top.

    • flex-end: Items at the bottom.

    • center: Items vertically centered.

flex-wrap Property (Container Property)

  • Purpose: Controls whether flex items are forced onto a single line or can wrap onto multiple lines.

  • Syntax: flex-wrap: value;

  • Values:

    1. nowrap (Default): All flex items will be on one line, possibly overflowing the container.

    2. wrap: Flex items will wrap onto multiple lines if necessary. Multiple lines are stacked along the cross-axis.

    3. wrap-reverse: Flex items will wrap onto multiple lines, but in reverse order along the cross-axis.

  • Use Case: Essential for responsive designs to prevent horizontal overflow on smaller screens.

  • Example:
    css #container { display: flex; flex-wrap: wrap; /* Allows items to wrap to next line */ width: 400px; /* Make container narrower than combined item widths */ } #container div { width: 150px; /* Example item width */ }

align-items Property (Container Property)

  • Purpose: Aligns flex items along the cross axis for the current line.

  • Syntax: align-items: value;

  • Common Values (assuming flex-direction: row;):

    1. stretch (Default): Items stretch to fill the container along the cross axis (respecting max-height/max-width).

    2. flex-start: Items are aligned to the start of the cross axis (top).

    3. flex-end: Items are aligned to the end of the cross axis (bottom).

    4. center: Items are centered along the cross axis.

    5. baseline: Items are aligned such that their baselines (text base) align.

  • Example (with flex-direction: row;):
    css #container { display: flex; height: 300px; /* Give container height for cross-axis alignment to be visible */ align-items: center; /* Vertically centers items within the container's height */ }

  • Behavior with column: If flex-direction: column;, align-items will align items horizontally (along the row).

align-content Property (Container Property)

  • Purpose: Aligns flex lines along the cross axis, when there is extra space in the cross axis and flex-wrap is set to wrap.

  • Syntax: align-content: value;

  • Values: Similar to justify-content (e.g., flex-start, flex-end, center, space-between, space-around, space-evenly, stretch (default)).

  • Key Distinction with align-items:

    • align-items aligns individual items within a flex line.

    • align-content aligns multiple lines of flex items (when wrapped) within the flex container.

  • Requires: flex-wrap: wrap; and sufficient extra space along the cross-axis.

  • Example: If items wrap onto two lines, align-content: center; would center both lines vertically within the container, distributing the extra space above and below the lines.

align-self Property (Item Property)

  • Purpose: Allows alignment of an individual flex item to be overridden along the cross axis.

  • Syntax: align-self: value;

  • Values: Same as align-items (e.g., flex-start, flex-end, center, stretch).

  • Priority: align-self has higher priority than align-items for the specific item it's applied to.

  • Example:
    css #container { display: flex; align-items: flex-start; /* All items align to the top */ } #box2 { align-self: flex-end; /* Overrides for box2, aligns it to the bottom */ }

flex-grow and flex-shrink Properties (Item Properties)

  • Dynamic Sizing: Flex items can automatically grow or shrink to fill available space or prevent overflow.

  • flex-grow:

    • Purpose: Specifies how much a flex item will grow relative to the rest of the flex items in the container when there is available extra space.

    • Syntax: flex-grow: number; (default is 0)

    • Behavior:

      • 0: The item will not grow.

      • 1 (Default if not specified in a growing scenario): The item will grow equally with other items having flex-grow: 1.

      • 2: The item will grow twice as much as an item with flex-grow: 1.

  • flex-shrink:

    • Purpose: Specifies how much a flex item will shrink relative to the rest of the flex items in the container when there is not enough available space.

    • Syntax: flex-shrink: number; (default is 1)

    • Behavior:

      • 0: The item will not shrink. It will maintain its original size, potentially causing overflow.

      • 1 (Default): The item will shrink equally with other items having flex-shrink: 1.

      • 2: The item will shrink twice as much as an item with flex-shrink: 1.

    • Note: Shrinking can sometimes be complex with specific width or height values; often, the effective width considers padding and borders as well.

  • Example:
    css #container { display: flex; width: 700px; /* Leave some extra space */ } #container div { width: 50px; /* Small base width */ } #box2 { flex-grow: 2; /* Box 2 will grow twice as much as others if space allows */ } #box1 { flex-shrink: 0; /* Box 1 will never shrink, even if it overflows */ width: 200px; /* Must have a width for shrink:0 to be meaningful */ }

Practice Set 6

Question 1: Create a navbar with four options in the form of anchor tags inside list items. Arrange them in a single line with equal spacing between them using Flexbox.
  • HTML:
    html ¨K209K

  • CSS:
    css .navbar { background-color: lightgray; padding: 10px; } .navbar ul { display: flex; /* Make the ul a flex container */ list-style-type: none; /* Remove default list bullets */ padding: 0; margin: 0; justify-content: space-evenly; /* Distribute items evenly */ align-items: center; /* Vertically center items in navbar */ } .navbar li a { text-decoration: none; /* Remove underline from links */ color: red; /* Example color */ padding: 5px 10px; /* Add some padding for clickable area */ }

Question 2: Use Flexbox to center one div inside another div.
  • HTML:
    html ¨K210K

  • CSS:
    css .outer { height: 400px; width: 400px; background-color: cornflowerblue; display: flex; /* Make the outer div a flex container */ justify-content: center; /* Horizontally center its content */ align-items: center; /* Vertically center its content */ } .inner { height: 100px; width: 100px; background-color: darkorchid; }

  • Explanation: Applying display: flex;, justify-content: center;, and align-items: center; to the parent container (.outer) is the most straightforward way to perfectly center a child element (.inner) both horizontally and vertically using Flexbox.

Question 3: Which has higher priority: align-items or align-self?
  • Answer: align-self has higher priority.

  • Explanation: align-items applies to all flex items within a container, setting their default alignment along the cross-axis. align-self is applied to individual flex items, allowing you to override the align-items value for that specific item. Therefore, align-self is more specific and takes precedence.

  • Example: If align-items: center; is on the container, but align-self: flex-start; is on one item, that one item will align to the start of the cross-axis, while others remain centered.

Level 5: Media Queries & Advanced CSS (Transitions, Transforms, Animations)

Media Queries

  • Purpose: Media queries are a CSS feature that allows you to apply different styles based on the characteristics of the device or viewport (e.g., screen width, height, orientation).

  • Responsiveness: They are crucial for creating responsive web pages that adapt and look good on various devices (desktops, laptops, tablets, mobile phones).

  • Why Responsive? People access websites on a multitude of screen sizes today, so a single design won't suffice.

  • Syntax:
    css @media screen and (condition) { /* CSS rules to apply when condition is true */ selector { property: value; } }

  • @media: Keyword to start a media query.

  • screen: Specifies the media type (other types exist, but screen is most common for web design).

  • condition: The characteristic to check.

  • Common Conditions (related to viewport dimensions):

    1. width: [value]px: Applies styles only when the viewport width is exactly [value]px.

      • Example: @media screen and (width: 600px)

    2. min-width: [value]px: Applies styles when the viewport width is at least [value]px (i.e., [value]px or wider).

      • Example: @media screen and (min-width: 600px) (for desktop-first design)

    3. max-width: [value]px: Applies styles when the viewport width is at most [value]px (i.e., [value]px or narrower).

      • Example: @media screen and (max-width: 600px) (for mobile-first design)

  • Combining Conditions (and keyword):

    • Purpose: To apply styles within a specific range of viewport dimensions.

    • Syntax: @media (min-width: [value1]px) and (max-width: [value2]px)

    • Example: @media (min-width: 200px) and (max-width: 300px) (styles apply only when width is between 200px and 300px inclusive).

  • Practical Example: Change font size based on screen width.

    /* Default styles for large screens */
    p { font-size: 1rem; }
    
    @media screen and (max-width: 768px) {
        /* Styles for screens smaller than or equal to 768px (tablets/phones) */
        p { font-size: 0.8rem; }
    }
    
    @media screen and (max-width: 480px) {
        /* Styles for screens smaller than or equal to 480px (mobile phones) */
        p { font-size: 0.7rem; }
    }
    
  • Developer Tools for Testing: Use the browser's developer tools (Inspect Element) and the responsive design mode (often an icon that looks like a phone and tablet) to test media queries by resizing the viewport and seeing the exact pixel dimensions.

Practice Set 7

Question: Create a div and add media queries to change its background color based on viewport width:
  • Less than 300px: Green

  • 300px to 400px: Pink

  • 400px to 600px: Red

  • Greater than 600px: Blue

  • HTML:
    ```html

    ```

  • CSS:

    div {
        height: 200px;
        width: 200px;
        background-color: chocolate; /* Default color if no media query matches */
    }
    
    @media (max-width: 299px) {
        div {
            background-color: green;
        }
    }
    
    @media (min-width: 300px) and (max-width: 399px) {
        div {
            background-color: pink;
        }
    }
    
    @media (min-width: 400px) and (max-width: 599px) {
        div {
            background-color: red;
        }
    }
    
    @media (min-width: 600px) {
        div {
            background-color: blue;
        }
    }
    
  • Testing: Resize your browser window and observe the div's background color changing according to the defined ranges.

Transitions Property

  • Purpose: Enables defining how an element smoothly changes its style from one state to another over a specified duration.

  • States: Elements can have different states.

    • Normal State: The default appearance.

    • hover State: When the mouse cursor is over the element.

    • active State: When the element is being clicked or activated.

    • focus State: When an element (like an input field) is selected by the user.

  • Pseudo-classes: Used to define styles for different states (e.g., :hover, :active).

    • Syntax: selector:pseudo-class { property: value; }

    • Example (:hover):
      css div { background-color: aquamarine; } div:hover { background-color: red; /* Changes color to red on hover */ color: white; /* Changes text color to white on hover */ font-size: 20px; /* Changes font size on hover */ } div:active { background-color: pink; /* Changes color to pink when clicked/held */ }

  • Transition Properties (applied to the normal state of the element):

    1. transition-property: Specifies which CSS property (or properties) the transition effect should be applied to.

      • Value: all (for all changing properties), or specific property names (e.g., background-color, font-size).

    2. transition-duration: Specifies how long the transition effect should take to complete.

      • Value: A time value (e.g., 2s for 2 seconds, 500ms for 500 milliseconds).

    3. transition-timing-function: Specifies the speed curve of the transition effect (how the animation progresses over time).

      • MDN Resource: Search "CSS transition-timing-function" on MDN for a visual guide.

      • Common Values:

        • ease (Default): Slow start, then fast, then slow end.

        • linear: Same speed from start to end.

        • ease-in: Slow start.

        • ease-out: Slow end.

        • ease-in-out: Slow start and end.

        • steps(N): Transition occurs in N discrete steps.

    4. transition-delay: Specifies a delay before the transition effect starts.

      • Value: A time value (e.g., 1s, 500ms).

  • Transition Shorthand:

    • Purpose: A concise way to set all transition properties in a single declaration.

    • Syntax: transition: [property] [duration] [timing-function] [delay];

    • Example:
      css div { transition: all 2s ease-in 1s; /* Applies to all properties, 2s duration, ease-in speed, 1s delay */ }

Transforms Property

  • Purpose: Allows you to visually manipulate elements in 2D or 3D space (rotate, scale, translate, skew).

  • Syntax: transform: function(value);

  • Key Functions:

    1. rotate(angle):

      • Purpose: Rotates an element around a fixed point (its center by default).

      • Value: An angle (e.g., 90deg for 90 degrees, 0.25turn for a quarter turn, 1.57rad for radians).

      • Axes of Rotation (3D - X, Y, Z):

        • rotateX(angle): Rotates around the horizontal (X) axis. Can make element appear to flip vertically.

        • rotateY(angle): Rotates around the vertical (Y) axis. Can make element appear to flip horizontally.

        • rotateZ(angle): Rotates around the Z-axis (coming out of the screen). This is equivalent to rotate(angle) in 2D.

        • Note on visibility: Rotating 90deg around X or Y axis can make the element appear to disappear as it becomes incredibly thin from the viewer's perspective.

      • Example: transform: rotate(45deg); or transform: rotateX(180deg);

    2. scale(x, y) or scale(factor):

      • Purpose: Changes the size of an element (magnifies or shrinks it).

      • Value(s):

        • factor: Scales both X and Y axes by the same factor (e.g., scale(2) doubles the size).

        • x, y: Scales X-axis by x factor and Y-axis by y factor (e.g., scale(1.5, 0.5) makes it 1.5 times wider and half as tall).

      • Individual Axis Scale: scaleX(factor) or scaleY(factor).

      • Example: transform: scale(1.5); or transform: scaleY(0.8);

    3. translate(x, y) or translate(value):

      • Purpose: Moves an element from its current position (effectively shifts it).

      • Value(s):

        • value: Moves along X-axis by value.

        • x, y: Moves along X-axis by x and Y-axis by y (e.g., translate(50px, -20px) moves 50px right and 20px up).

        • Positive values move right/down; negative values move left/up.

      • Individual Axis Translate: translateX(value) or translateY(value).

      • Example: transform: translateX(100px); or transform: translateY(-50%);

    4. skew(angleX, angleY) or skew(angle):

      • Purpose: Skews an element along the X and/or Y axes, giving it a tilted or slanted appearance.

      • Value(s): Angles (e.g., 30deg).

        • angle: Skews both X and Y axes by the same angle.

        • angleX, angleY: Skews X-axis by angleX and Y-axis by angleY.

      • Individual Axis Skew: skewX(angle) or skewY(angle).

      • Example: transform: skew(30deg); or transform: skewY(-15deg);

  • Combining Transforms: Multiple transform functions can be chained within a single transform property value.

    • Example: transform: rotate(45deg) scale(1.2) translateX(10px);

  • Integration with Transitions: Transforms are often combined with transitions :hover pseudo-classes to create smooth interactive effects.
    css div { transition: transform 0.5s ease-out; /* Smooth transition for transform changes */ } div:hover { transform: rotate(180deg) scale(1.1); /* Rotate and slightly grow on hover */ }

Animations Property

  • Purpose: Allows for complex, multi-stage animations by defining a set of keyframes and then applying them to an element.

  • Keyframes (@keyframes):

    • Purpose: Defines the intermediate steps (or frames) in a CSS animation sequence. It acts as a blueprint for the animation.

    • Syntax:
      css @keyframes animation-name { from { /* styles at the start of the animation (0%) */ } to { /* styles at the end of the animation (100%) */ } /* Or use percentages for intermediate steps */ 0% { /* styles at 0% of animation */ } 50% { /* styles at 50% of animation */ } 100% { /* styles at 100% of animation */ } }

    • animation-name: A custom name for your animation.

    • from (or 0%): The initial state of the animation.

    • to (or 100%): The final state of the animation.

    • Note: @keyframes only defines the animation; it doesn't apply it to an element.

  • Animation Properties (applied to the element being animated):

    1. animation-name: Refers to the name of the @keyframes rule to be applied.

    2. animation-duration: Specifies how long an animation takes to complete one cycle.

    3. animation-timing-function: Defines the speed curve of the animation (same values as transition-timing-function).

    4. animation-delay: Specifies when the animation should start (delay before execution).

    5. animation-iteration-count: Specifies how many times an animation should play.

      • Value: A number, or infinite (to play indefinitely).

    6. animation-direction: Specifies whether the animation should play forwards, backwards, or alternate directions.

      • Values:

        • normal (Default): Plays forward each cycle.

        • reverse: Plays backward each cycle (from to to from).

        • alternate: Plays forward first, then backward, then forward, etc.

        • alternate-reverse: Plays backward first, then forward, then backward, etc.

  • Animation Shorthand:

    • Syntax: animation: [name] [duration] [timing-function] [delay] [iteration-count] [direction];

    • Order: The order of values matters, especially for duration and delay (duration comes first).

    • Example (for @keyframes spin):
      css div { animation: spin 3s ease-in 1s infinite alternate; /* name, duration, timing, delay, iteration, direction */ }

Practical Animation Example (Blinking Light/Loader):

  • HTML: <div></div>

  • CSS:

    div {
        height: 100px;
        width: 100px;
        border-radius: 50%; /* Make it circular */
        background-color: aquamarine;
        animation: blink 1s infinite alternate;
    }
    
    @keyframes blink {
        from { background-color: aquamarine; }
        to { background-color: red; }
    }
    

Practice Set 8

Question: Create a simple loader using CSS.
  • Steps:

    1. Create a div with a circular shape.

    2. Give it a thick border from only one end (e.g., border-top).

    3. Create an animation that transforms it from 0deg to 360deg.

    4. Use the animation property to make the div spin infinitely.

  • HTML:
    ```html

    ```

  • CSS:

    .loader {
        height: 100px;
        width: 100px;
        border-radius: 50%; /* Step 1: Circular shape */
        border: 20px solid rgba(0, 0, 0, 0.1); /* Semi-transparent base border */
        border-top: 20px solid #3498db; /* Step 2: Thick border from one end (blue) */
        /* Or use individual border properties for more control: */
        /* border-top-color: #3498db; */
        /* border-right-color: transparent; */
        /* border-bottom-color: transparent; */
        /* border-left-color: transparent; */
    animation: spin 1s linear infinite; /* Step 4: Apply animation */
    

    } @keyframes spin { 0% { transform: rotate(0deg); } /* Step 3: From 0deg */ 100% { transform: rotate(360deg); } /* Step 3: To 360deg */ }

  • Explanation:

    • The border and border-top create the visual of a partial, colored border that looks like it's spinning.

    • animation: spin 1s linear infinite; tells the .loader to use the @keyframes spin rule, complete one cycle in 1 second, at a linear speed, and repeat indefinitely.

    • linear timing function is used to ensure a constant spinning speed, making it look smoother as a loader.

Project: Amazon.in Clone

  • Objective: To build a clone of Amazon.com (global version) homepage, applying all previously learned CSS concepts.

  • Scope: Focus on replicating the most important UI elements to give a realistic look and feel. This will be a substantial HTML/CSS based front-end project suitable for a resume.

  • New Concepts: A few new concepts will be introduced during the project build.

1. Icons

  • Importance: Icons are crucial for a modern UI (e.g., search icon, cart icon, location icon).

  • Resource: Font Awesome (fontawesome.com) is a widely used library for scalable vector icons.

    • Offers many free and open-source icons.

  • Integration:

    1. Link Font Awesome CDN: Include the Font Awesome CSS library in your HTML <head>.

      • Search for "Font Awesome CDNJS" on Google.

      • Go to cdnjs.com and copy the <link> tag for Font Awesome (usually the latest version).

      • CDN (Content Delivery Network): A system of distributed servers that deliver web content to users based on their geographic location, speeding up page load times.

      • Paste the copied <link> tag into your index.html's <head> section, above your custom style.css.

    2. Add Icons:

      • Go to fontawesome.com/icons and search for desired icons.

      • Click on an icon, then click the provided <i class="..."></i> HTML snippet to copy it.

      • Paste the HTML snippet into your index.html where you want the icon to appear.

      • Example: <i class="fa-solid fa-heart"></i> for a heart icon.

2. Project Setup

  • Folder Structure: In your "Classroom" folder, create index.html and style.css.

  • Images: Download necessary images (e.g., Amazon logo, various product images, hero section image) directly from Amazon.com (right-click -> "Save Image As…") and place them in your project folder.

3. Global CSS (Initial Setup in style.css)

  • CSS Reset: ```css

    • {
      margin: 0;
      padding: 0;
      font-family: Arial, sans-serif; /* Use Arial as a clean fallback / box-sizing: border-box; / Crucial for consistent box model behavior */
      }
      ```

    • margin: 0; padding: 0;: Resets default browser margins and padding, ensuring you have full control over spacing.

    • font-family: Arial, sans-serif;: Sets a default font. (Amazon uses a custom font, but Arial is a good substitute).

    • box-sizing: border-box;: This is very important. It ensures that an element's padding and border are included in its total width and height. Without this, padding and border would add on top of the specified width/height, making layout calculations more complex.

4. Building the Navigation Bar (Header)

  • HTML Structure (Inside <body>):

    <header>
        <div class="navbar">
            <!-- Nav Logo Box -->
            <div class="nav-bar-logo border">
                <div class="logo"></div>
            </div>
        &lt;!-- Nav Address Box --&gt;
        &lt;div class="nav-address border"&gt;
            &lt;p class="add-first"&gt;Deliver to&lt;/p&gt;
            &lt;div class="address-icon"&gt;
                &lt;i class="fa-solid fa-location-dot"&gt;&lt;/i&gt;
                &lt;p class="add-second"&gt;India&lt;/p&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    
        &lt;!-- Nav Search Box --&gt;
        &lt;div class="nav-search"&gt;
            &lt;select class="search-select"&gt;
                &lt;option&gt;All&lt;/option&gt;
            &lt;/select&gt;
            &lt;input placeholder="Search Amazon.in" class="search-input"&gt;
            &lt;div class="search-icon"&gt;
                &lt;i class="fa-solid fa-magnifying-glass"&gt;&lt;/i&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    
        &lt;!-- Nav Sign In Box --&gt;
        &lt;div class="nav-signin border"&gt;
            &lt;p&gt;&lt;span&gt;Hello, Sign in&lt;/span&gt;&lt;/p&gt;
            &lt;p class="nav-second"&gt;Account &amp; Lists&lt;/p&gt;
        &lt;/div&gt;
    
        &lt;!-- Nav Returns &amp; Orders Box --&gt;
        &lt;div class="nav-returns border"&gt;
            &lt;p&gt;&lt;span&gt;Returns&lt;/span&gt;&lt;/p&gt;
            &lt;p class="nav-second"&gt;&amp; Orders&lt;/p&gt;
        &lt;/div&gt;
    
        &lt;!-- Nav Cart Box --&gt;
        &lt;div class="nav-cart border"&gt;
            &lt;i class="fa-solid fa-cart-shopping"&gt;&lt;/i&gt;
            &lt;div class="cart-text"&gt;Cart&lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    

    </header>

  • CSS for Nav Bar (.navbar):

    • Set height: 60px; and background-color: #0F1111; (dark).

    • Set color: white; for default text within the navbar.

    • Use display: flex; and align-items: center; to arrange items horizontally and vertically center them.

    • Use justify-content: space-evenly; to distribute space horizontally between major sections.

    • .border class for hover effect:
      css .border { border: 1.5px solid transparent; /* default transparent border */ } .border:hover { border: 1.5px solid white; /* white border on hover */ }

  • CSS for Nav Logo (.nav-bar-logo, .logo):

    • Set .logo to background-image: url('amazon_logo.png');, background-size: cover;, height: 50px;, width: 100px;.

  • CSS for Nav Address (.nav-address, .add-first, .address-icon, .add-second):

    • nav-address: Container for address, use display: flex; flex-direction: column; if content is vertically stacked.

    • add-first: color: #CCCCCC; font-size: 0.85rem;

    • address-icon: To align icon and text horizontally: display: flex; align-items: center;

    • add-second: font-size: 1rem; (or slightly larger, e.g., 1.1rem), font-weight: 700;

    • Adjust margin-left for spacing between icon and text.

  • CSS for Nav Search (.nav-search, .search-select, .search-input, .search-icon):

    • nav-search: display: flex;, height: 40px;, width: 620px;, border-radius: 4px;.

    • search-select: background-color: #F3F3F3;, width: 50px;, text-align: center;, border-top-left-radius: 4px;, border-bottom-left-radius: 4px;, border: none; (to remove default select border).

    • search-input: width: 100%; (or flex-grow: 1; so it takes available space), font-size: 1rem;, border: none;

    • search-icon: background-color: #FEBD69; (orange), width: 45px;, display: flex; justify-content: center; align-items: center;, font-size: 1.2rem;, color: #0F1111; (dark color for icon), border-top-right-radius: 4px;, border-bottom-right-radius: 4px;

    • nav-search:hover: Add border: 2px solid orange; to simulate Amazon's search bar hover effect.

  • CSS for Nav Sign In & Returns (.nav-signin, .nav-returns, .nav-second):

    • Similar structure to Nav Address: two lines of text.

    • nav-second: font-size: 1rem;, font-weight: 700;

    • Span text (first line): font-size: 0.7rem; color: #CCCCCC;

  • CSS for Nav Cart (.nav-cart, .cart-text):

    • nav-cart: display: flex; align-items: flex-end; (aligns cart text to bottom of icon).

    • i (icon within nav-cart): font-size: 1.7rem;

    • .cart-text: font-size: 0.85rem;, font-weight: 700;

5. Building the Panel (Sub-Navigation)

  • HTML Structure (Inside header, after .navbar):
    html ¨K268K

  • CSS for Panel (.panel):

    • background-color: #222f3d; (darker blue/gray).

    • height: 40px;

    • display: flex; align-items: center; justify-content: space-evenly;

    • color: white; for text.

  • CSS for Panel Options (.panel-options):

    • width: 70%; (to expand and push other items to sides).

    • display: flex; (to arrange its child paragraphs horizontally).

    • gap: 15px; (to add space between options).

    • font-size: 0.8rem;

  • CSS for Panel All (.panel-ops):

    • font-weight: 700;

    • font-size: 0.9rem;

    • Adjust margin-left for space for the icon.

6. Building the Hero Section

  • HTML Structure (After </header>):
    html ¨K272K

  • CSS for Hero Section (.hero-section):

    • background-image: url('hero_image.jpg');

    • background-size: cover;

    • height: 350px; (adjust as needed for visual appeal).

    • display: flex; justify-content: center; align-items: flex-end; (to push the message box to the bottom center).

  • CSS for Hero Message (.hero-msg):

    • background-color: white;

    • color: black;

    • height: 40px;

    • display: flex; justify-content: center; align-items: center; (to center text within).

    • width: 80%; (to prevent it from spanning full width).

    • font-size: 0.85rem;

    • margin-bottom: 25px; (to lift it slightly from the bottom edge of the hero section).

    • hero-msg a: color: #007185; (Amazon's link blue).

7. Building the Shop Section (Product Boxes)

  • HTML Structure (After </div> for .hero-section):
    html ¨K275K

  • CSS for Shop Section (.shop-section):

    • background-color: #e2e7e6; (light gray).

    • display: flex; flex-wrap: wrap; justify-content: space-evenly; (to arrange boxes in rows, with even spacing).

    • padding: 20px 0; (vertical padding).

  • CSS for Individual Boxes (.box):

    • height: 400px;

    • width: 23%; (approx 23% to fit 4 boxes with spacing, adjust if needed).

    • background-color: white;

    • padding: 20px 0 15px; (top, LR, bottom padding).

    • margin-top: 15px; (space between rows if wrapped).

  • CSS for Box Content (.box-content):

    • margin-left: 10px; margin-right: 10px; (internal horizontal spacing).

    • box-content h2: font-size: 1.3rem; margin-bottom: 5px; (or similar).

    • box-img: height: 300px; (or adjust height for image display), background-size: cover; margin-top: 10px; margin-bottom: 10px; (vertical spacing for image).

    • box-content p a: color: #007185; (Amazon's link blue).

8. Building the Footer

  • HTML Structure (After </div> for .shop-section):

    <footer>
        <!-- Footer Panel 1: Back to Top -->
        <div class="foot-panel1">
            Back To Top
        </div>
    &lt;!-- Footer Panel 2: Get to Know Us, Make Money with Us, etc. --&gt;
    &lt;div class="foot-panel2"&gt;
        &lt;ul&gt;
            &lt;p&gt;Get to Know Us&lt;/p&gt;
            &lt;li&gt;&lt;a href="#"&gt;Careers&lt;/a&gt;&lt;/li&gt;
            &lt;li&gt;&lt;a href="#"&gt;Blog&lt;/a&gt;&lt;/li&gt;
            &lt;!-- ... more list items ... --&gt;
        &lt;/ul&gt;
        &lt;!-- Repeat ul for other categories --&gt;
    &lt;/div&gt;
    
    &lt;!-- Footer Panel 3: Amazon Logo, Language, Currency --&gt;
    &lt;div align="center" class="foot-panel3"&gt;
        &lt;div class="logo"&gt;&lt;/div&gt; &lt;!-- Reusing the logo class --&gt;
        &lt;!-- Add language selector, currency selector here --&gt;
    &lt;/div&gt;
    
    &lt;!-- Footer Panel 4: Copyright, Conditions --&gt;
    &lt;div class="foot-panel4"&gt;
       &lt;div class="pages"&gt;
            &lt;a href="#"&gt;Conditions of Use&lt;/a&gt;
            &lt;a href="#"&gt;Privacy Notice&lt;/a&gt;
            &lt;a href="#"&gt;Your Ads Privacy Choices&lt;/a&gt;
       &lt;/div&gt;
       &lt;div class="copyright"&gt;
            © 1996-2023, Amazon.com, Inc. or its affiliates
       &lt;/div&gt;
    &lt;/div&gt;
    

    </footer>

  • CSS for Foot Panel 1 (.foot-panel1):

    • background-color: #37475A; (dark bluish-gray).

    • color: white; height: 50px;

    • display: flex; justify-content: center; align-items: center; (to center the text).

    • font-size: 0.7rem; margin-top: 15px; (space from shop section).

  • CSS for Foot Panel 2 (.foot-panel2):

    • background-color: #222f3d; (darker blue/gray).

    • color: white; height: 300px;

    • display: flex; justify-content: space-evenly; (to space out lists horizontally).

    • .foot-panel2 ul p: font-weight: 700; font-size: 0.9rem; margin-bottom: 10px;

    • .foot-panel2 ul a: display: block; font-size: 0.85rem; color: #DDDDDD; margin-bottom: 8px; text-decoration: none; (display block makes links stack vertically).

  • CSS for Foot Panel 3 (.foot-panel3):

    • background-color: #222f3d; (same as panel 2).

    • border-top: 0.5px solid #BBBBBB; (thin gray line).

    • height: 70px;

    • display: flex; justify-content: center; align-items: center;

    • .logo: Reusing logo class from navbar, margin-right: 20px;.

    • (Add styles for language/currency selectors if included)

  • CSS for Foot Panel 4 (.foot-panel4):

    • background-color: #0F1111; (darkest color, same as navbar).

    • color: white;

    • height: 80px;

    • font-size: 0.7rem;

    • text-align: center; (to center copyright text).

    • .pages: padding-top: 25px;

    • .pages a: color: white; text-decoration: none; margin-right: 15px;

    • .copyright: margin-top: 5px;

Conclusion & Further Exploration

  • Project Completion: The clone's layout is visually similar to Amazon.com. This is a solid front-end project to add to your resume.

  • Next Steps: Learning JavaScript would allow you to add interactivity and functionality to the clone (e.g., clicking buttons, dynamic content).

  • Continuous Learning: Always explore documentation (like MDN), experiment with code, try cloning other websites, and push beyond just following tutorials. Hands-on practice and debugging are key to becoming a proficient developer.