0% found this document useful (0 votes)
9 views

Comprehensive Guide to Advanced CSS

Uploaded by

contraste visual
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Comprehensive Guide to Advanced CSS

Uploaded by

contraste visual
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Comprehensive Guide to Advanced CSS

Welcome to the Advanced CSS guide! Building upon the fundamentals of CSS, this guide
delves into more sophisticated techniques and concepts that empower you to create dynamic,
responsive, and maintainable web designs. Whether you're aiming to master complex layouts,
optimize performance, or enhance accessibility, this guide provides the knowledge and practical
examples necessary to elevate your CSS skills to the next level.

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

1
This guide includes code examples, detailed explanations, multiple-choice questions with
answers, comprehensive examples, and exercises to reinforce your learning.

Comprehensive Guide to Advanced CSS 1


1. Advanced Layout Techniques 4
CSS Grid Layout 4
Key Concepts: 4
Basic Example: 5
Flexbox In-Depth 6
Key Concepts: 6
Basic Example: 6
Comparing Grid and Flexbox 7
2. CSS Variables (Custom Properties) 8
Defining and Using Variables 8
Defining Variables 8
Using Variables 8
Scope and Inheritance 9
Fallback Values 9
JavaScript Integration 10
3. Advanced Selectors 11
Attribute Selectors 11
Basic Attribute Selector 11
Partial Attribute Matching 11
Pseudo-classes 12
Common Pseudo-classes: 12
Pseudo-elements 12
Common Pseudo-elements: 13
Combinators and Specificity 13
Types of Combinators: 13
4. Responsive Design Techniques 15
Media Queries 15
Mobile-First Design 15
Responsive Units 16
Common Responsive Units: 16
Container Queries 17
5. CSS Functions 17
calc() 17
clamp() 18
min() and max() 18
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

2
var() 19
6. Advanced Typography 19
Variable Fonts 20
Benefits: 20
Font Loading Strategies 20
Strategies: 21
Text Effects with CSS 21
Common Text Effects: 21
7. CSS Architecture 22
BEM (Block Element Modifier) 22
Structure: 23
OOCSS (Object-Oriented CSS) 23
Principles: 23
SMACSS (Scalable and Modular Architecture for CSS) 25
Categories: 25
8. CSS Performance Optimization 26
Minimizing Repaints and Reflows 26
Tips: 26
Optimizing Selectors 27
Best Practices: 27
Critical CSS 28
Steps: 28
Using CSS Containment 28
9. CSS Houdini 29
Introduction to Houdini 29
Key APIs: 29
Custom Paint API 29
Layout API 31
10. CSS for Accessibility 31
Ensuring Color Contrast 31
Focus States 32
Avoiding Motion Sensitivity Issues 32
11. CSS Filters and Blend Modes 32
Filter Property 33
Mix-blend-mode and Background-blend-mode 33
mix-blend-mode 34
background-blend-mode 34
12. Best Practices and Common Pitfalls 35
Best Practices 35
Common Pitfalls 37
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

3
13. Multiple Choice Questions 38
Question 1 38
Question 2 38
Question 3 39
Question 4 39
Question 5 40
Question 6 40
Question 7 40
Question 8 41
Question 9 41
Question 10 42
Question 11 42
Question 12 42
Question 13 43
Question 14 43
Question 15 43
14. Exercises 44
Exercise 1: Create a Responsive Grid Layout 44
Exercise 2: Implement CSS Variables for Theming 45
Exercise 3: Build an Accessible Navigation Menu 46
Exercise 4: Create a Custom Checkbox with CSS 48
Exercise 5: Develop a Responsive Typography System 50
15. Conclusion 51
Next Steps 51

1. Advanced Layout Techniques


Creating complex and responsive layouts is a cornerstone of modern web design. Advanced
CSS layout techniques, such as CSS Grid Layout and Flexbox, offer powerful tools to achieve
intricate designs with ease.

CSS Grid Layout

CSS Grid Layout is a two-dimensional layout system that allows developers to create complex
grid-based designs. It excels in managing both rows and columns, making it ideal for building
responsive layouts.

Key Concepts:

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

4
● Grid Container: The parent element where display: grid or display:
inline-grid is applied.
● Grid Items: The direct children of the grid container.
● Grid Lines: The dividing lines that make up the structure of the grid.
● Grid Areas: Rectangular areas bounded by four grid lines.
● Grid Tracks: The space between two adjacent grid lines, defining rows or columns.

Basic Example:

HTML:

<div class="grid-container">
<div class="grid-item item1">1</div>
<div class="grid-item item2">2</div>
<div class="grid-item item3">3</div>
<div class="grid-item item4">4</div>
</div>

CSS:

.grid-container {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 20px;
padding: 20px;
}
.grid-item {
background-color: #3498db;
color: white;
font-size: 2em;
display: flex;
align-items: center;
justify-content: center;
}

Explanation:

● display: grid; establishes the grid container.


● grid-template-columns: repeat(2, 1fr); creates two columns with equal
width.

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

5
● grid-gap: 20px; adds space between grid items.
● Each .grid-item is styled for visual clarity.

Visual Outcome:

A simple 2x2 grid with four blue boxes numbered 1 to 4, evenly spaced with gaps.

Flexbox In-Depth

Flexbox is a one-dimensional layout system optimized for arranging items in rows or columns.
It's highly effective for distributing space and aligning items within a container.

Key Concepts:

● Flex Container: The parent element where display: flex or display:


inline-flex is applied.
● Flex Items: The direct children of the flex container.
● Main Axis: The primary axis along which flex items are laid out (row or column).
● Cross Axis: The axis perpendicular to the main axis.
● Flex Direction: Determines the direction of the main axis (row, row-reverse,
column, column-reverse).
● Justify Content: Aligns items along the main axis.
● Align Items: Aligns items along the cross axis.
● Flex Grow, Shrink, Basis: Controls how flex items grow, shrink, and their initial size.

Basic Example:

HTML:

<div class="flex-container">
<div class="flex-item">A</div>
<div class="flex-item">B</div>
<div class="flex-item">C</div>
</div>

CSS:

.flex-container {
display: flex;
justify-content: space-around;
align-items: center;
height: 200px;
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

6
background-color: #ecf0f1;
}
.flex-item {
background-color: #2ecc71;
color: white;
padding: 20px;
font-size: 1.5em;
border-radius: 5px;
}

Explanation:

● display: flex; establishes the flex container.


● justify-content: space-around; distributes space evenly around flex items.
● align-items: center; vertically centers items within the container.
● Each .flex-item is styled for visibility.

Visual Outcome:

Three green boxes labeled A, B, and C are evenly spaced horizontally and centered vertically
within a light gray container.

Comparing Grid and Flexbox


Feature CSS Grid Layout Flexbox

Dimension Two-dimensional (rows and One-dimensional (rows or columns)


columns)

Use Case Complex, grid-based layouts Aligning items, simpler layouts

Control Precise placement of items within a Dynamic distribution of space among


grid items

Overlap Supports overlapping items via grid Limited support for overlapping items
areas

Browser Widely supported in modern Fully supported across all modern


Support browsers browsers

Choosing Between Grid and Flexbox:

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

7
● Use Grid when dealing with complex layouts that require control over both rows and
columns.
● Use Flexbox for simpler, one-dimensional layouts, such as navigation bars or aligning
items within a container.

2. CSS Variables (Custom Properties)


CSS Variables, also known as Custom Properties, allow you to store values that can be
reused throughout your CSS. They enhance maintainability and scalability by reducing
redundancy and facilitating theme management.

Defining and Using Variables

Defining Variables

Variables are defined within a selector using the -- prefix.

Example:

:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--font-size: 16px;
}

● :root is a pseudo-class representing the root element (typically <html>), making


variables globally accessible.
● Variables can also be defined within specific selectors for scoped usage.

Using Variables

Variables are accessed using the var() function.

Example:

body {
background-color: var(--primary-color);
font-size: var(--font-size);
}
.button {
background-color: var(--secondary-color);
color: white;
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

8
padding: 10px 20px;
border: none;
border-radius: 4px;
}

Explanation:

● var(--primary-color) retrieves the value of --primary-color defined in :root.


● If a variable is not defined in the current scope, CSS will look up the inheritance chain.

Scope and Inheritance

Variables can be scoped to specific elements, allowing for flexibility in design.

Example:

:root {
--main-bg-color: white;
}
.dark-mode {
--main-bg-color: #2c3e50;
}
.content {
background-color: var(--main-bg-color);
color: black;
}
.dark-mode .content {
color: white;
}

Explanation:

● The .dark-mode class overrides --main-bg-color for elements within its scope.
● .content uses var(--main-bg-color) which changes based on whether
.dark-mode is applied.

Fallback Values

The var() function can accept a fallback value if the variable is not defined.

Syntax:
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

9
var(--variable-name, fallback-value)

Example:

.header {
color: var(--header-color, #333333);
}

Explanation:

● If --header-color is not defined, the color defaults to #333333.

JavaScript Integration

CSS Variables can be dynamically manipulated using JavaScript, enabling real-time theming
and interactivity.

Example:

<button id="toggleTheme">Toggle Theme</button>


<div class="box">Content Box</div>
:root {
--bg-color: #ffffff;
--text-color: #000000;
}
.dark-theme {
--bg-color: #2c3e50;
--text-color: #ecf0f1;
}
.box {
background-color: var(--bg-color);
color: var(--text-color);
padding: 20px;
border-radius: 5px;
transition: background-color 0.3s ease, color 0.3s ease;
}
const toggleButton = document.getElementById('toggleTheme');
const box = document.querySelector('.box');
toggleButton.addEventListener('click', () => {
document.documentElement.classList.toggle('dark-theme');
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

10
});

Explanation:

● Clicking the "Toggle Theme" button adds or removes the .dark-theme class on the
<html> element.
● This class change updates the CSS Variables --bg-color and --text-color,
resulting in a theme switch.

3. Advanced Selectors
Advanced CSS selectors provide powerful ways to target elements based on attributes, states,
and relationships, enabling more precise and efficient styling.

Attribute Selectors

Attribute selectors target elements based on the presence or value of HTML attributes.

Basic Attribute Selector

Syntax:

element[attribute] { /* styles */ }

Example:

input[type="text"] {
border: 1px solid #ccc;
padding: 10px;
}

Partial Attribute Matching

● Starts With (^=): [attr^="value"] selects elements with attribute values starting
with "value".
● Ends With ($=): [attr$="value"] selects elements with attribute values ending with
"value".
● Contains (*=): [attr*="value"] selects elements with attribute values containing
"value".

Example:

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

11
a[href^="https://"] {
color: green;
}
img[src$=".png"] {
border: 2px solid #f1c40f;
}
div[class*="container"] {
margin: 0 auto;
}

Pseudo-classes

Pseudo-classes target elements based on their state or position within the DOM.

Common Pseudo-classes:

● :nth-child(n): Selects the nth child element.


● :not(selector): Selects elements not matching the specified selector.
● :hover: Selects elements when hovered over.
● :focus: Selects elements when focused.
● :active: Selects elements when active (e.g., being clicked).
● :first-child and :last-child: Selects the first and last child elements.

Example:

/* Style every even list item */


li:nth-child(even) {
background-color: #f9f9f9;
}
/* Style all paragraphs except those with class 'intro' */
p:not(.intro) {
color: #555555;
}
/* Change button color on hover */
button:hover {
background-color: #e74c3c;
}

Pseudo-elements
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

12
Pseudo-elements target specific parts of an element, such as before or after its content.

Common Pseudo-elements:

● ::before: Inserts content before the element's content.


● ::after: Inserts content after the element's content.
● ::first-letter: Styles the first letter of the element's content.
● ::first-line: Styles the first line of the element's content.

Example:

/* Add an asterisk before required form labels */


label.required::before {
content: "* ";
color: red;
}
/* Insert a decorative line after headings */
h2::after {
content: "";
display: block;
width: 50px;
height: 3px;
background-color: #3498db;
margin-top: 5px;
}

Combinators and Specificity

Combinators define relationships between selectors, enabling more precise targeting.

Types of Combinators:

● Descendant ( ): Selects elements nested within another element.


● Child (>): Selects direct child elements.
● Adjacent Sibling (+): Selects the element immediately following another.
● General Sibling (~): Selects all elements following another.

Example:

/* Descendant combinator */
nav a {
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

13
color: #2c3e50;
}
/* Child combinator */
ul > li {
list-style: none;
}
/* Adjacent sibling combinator */
h1 + p {
margin-top: 0;
}
/* General sibling combinator */
h2 ~ p {
color: #7f8c8d;
}

Specificity:

CSS specificity determines which styles are applied when multiple selectors target the same
element. It's calculated based on the types of selectors used:

● Inline styles: Highest specificity.


● IDs: High specificity.
● Classes, attributes, and pseudo-classes: Medium specificity.
● Elements and pseudo-elements: Low specificity.

Example:

/* Lower specificity */
p {
color: blue;
}
/* Higher specificity */
.highlight {
color: red;
}
/* Even higher specificity */
#main-content p {
color: green;
}

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

14
4. Responsive Design Techniques
Responsive design ensures that web content adapts seamlessly across various devices and
screen sizes, providing an optimal user experience.

Media Queries

Media queries apply CSS rules based on device characteristics, such as screen width, height,
orientation, and resolution.

Syntax:

@media (condition) {
/* CSS rules */
}

Example:

/* Apply styles for screens wider than 768px */


@media (min-width: 768px) {
.sidebar {
display: block;
}
}
/* Apply styles for screens 768px wide or narrower */
@media (max-width: 768px) {
.sidebar {
display: none;
}
}

Combining Conditions:

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


.container {
width: 80%;
}
}

Mobile-First Design
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

15
Mobile-First Design involves designing for smaller screens first and progressively enhancing
the layout for larger screens. This approach ensures better performance and usability on mobile
devices.

Example:

/* Base styles for mobile */


.container {
padding: 10px;
}
/* Enhancements for tablets and above */
@media (min-width: 768px) {
.container {
padding: 20px;
}
}
/* Enhancements for desktops and above */
@media (min-width: 1024px) {
.container {
padding: 30px;
}
}

Responsive Units

Responsive units scale elements based on viewport size or relative measurements, ensuring
adaptability across devices.

Common Responsive Units:

● Viewport Width (vw) and Height (vh): Percentage of the viewport's width and height.
● Relative to Root Font Size (rem): Scales based on the root (<html>) font size.
● Relative to Parent Font Size (em): Scales based on the parent element's font size.
● Percentage (%): Relative to the parent element's dimensions.

Example:

/* Using viewport units */


.header {
height: 10vh;

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

16
font-size: 2vw;
}
/* Using rem units */
body {
font-size: 16px;
}
h1 {
font-size: 2.5rem; /* 40px */
}

Container Queries

Container Queries allow styling elements based on the size of their container rather than the
viewport. Although not widely supported yet, they offer powerful capabilities for
component-based design.

Example:

/* Hypothetical syntax as Container Queries are still experimental */


@container (min-width: 300px) {
.card {
display: flex;
}
}

Note: As of now, container queries are experimental and may not be supported in all browsers.
Always check compatibility before using them in production.

5. CSS Functions
CSS offers various functions that provide dynamic and flexible styling capabilities, enabling
calculations, value manipulations, and more.

calc()

The calc() function allows mathematical calculations to determine CSS property values,
combining different units.

Syntax:

property: calc(expression);
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

17
Example:

.container {
width: calc(100% - 40px);
height: calc(100vh - 60px);
}

Explanation:

● Calculates the container's width as the full viewport width minus 40 pixels.
● Useful for creating layouts that adapt to varying sizes.

clamp()

The clamp() function restricts a value between a defined minimum and maximum, ensuring
responsiveness and accessibility.

Syntax:

property: clamp(min, preferred, max);

Example:

.heading {
font-size: clamp(1.5rem, 2.5vw, 2.5rem);
}

Explanation:

● Sets the font size to a minimum of 1.5rem, scales with viewport width (2.5vw), and caps
at 2.5rem.
● Ensures text remains readable across devices.

min() and max()

The min() and max() functions return the smallest or largest value among a list of
expressions, respectively.

Syntax:

property: min(expression1, expression2, ...);


property: max(expression1, expression2, ...);

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

18
Example:

.box {
width: min(50%, 300px);
height: max(200px, 30vh);
}

Explanation:

● width: min(50%, 300px); ensures the box is no wider than 300px or half the
parent container, whichever is smaller.
● height: max(200px, 30vh); ensures the box is at least 200px tall or 30% of the
viewport height, whichever is larger.

var()

The var() function accesses the value of a CSS Variable (Custom Property).

Syntax:

property: var(--variable-name, fallback);

Example:

:root {
--main-color: #2980b9;
}
.button {
background-color: var(--main-color);
color: white;
padding: 10px 20px;
}

Explanation:

● Retrieves the value of --main-color and applies it to the button's background color.
● If --main-color is not defined, a fallback value can be specified.

6. Advanced Typography

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

19
Typography plays a crucial role in web design, influencing readability, aesthetics, and user
experience. Advanced CSS techniques enable nuanced control over text presentation.

Variable Fonts

Variable Fonts are single font files that behave like multiple fonts, allowing for adjustments in
weight, width, slant, and other attributes dynamically.

Benefits:

● Performance: Reduces the number of font files needed, lowering load times.
● Flexibility: Enables on-the-fly adjustments to font properties.
● Design Precision: Allows for fine-tuned typography without multiple font styles.

Example:

@font-face {
font-family: 'Roboto Variable';
src: url('Roboto-VariableFont_wght.ttf') format('truetype');
font-weight: 100 900;
}
body {
font-family: 'Roboto Variable', sans-serif;
font-weight: 400; /* Normal */
}
h1 {
font-weight: 700; /* Bold */
}
.light-text {
font-weight: 300; /* Light */
}

Explanation:

● Defines a variable font with a weight range from 100 to 900.


● Different elements use various weights without needing separate font files.

Font Loading Strategies

Efficient font loading enhances performance and user experience by preventing issues like
Flash of Unstyled Text (FOUT) or Flash of Invisible Text (FOIT).

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

20
Strategies:
Preloading Fonts:

<link rel="preload" href="fonts/Roboto.woff2" as="font"


type="font/woff2" crossorigin>
Using font-display:

@font-face {
font-family: 'Roboto';
src: url('Roboto.woff2') format('woff2');
font-display: swap;
}

○ Values:
■ auto: Default behavior.
■ block: Blocks text until font loads, potentially causing FOIT.
■ swap: Displays fallback text immediately and swaps to the custom font
once loaded.
■ fallback: Similar to swap but with shorter block period.
■ optional: Allows the browser to use fallback font if the custom font
doesn't load quickly.

Text Effects with CSS

CSS enables various text effects that enhance visual appeal without relying on images or
JavaScript.

Common Text Effects:


Text Shadows:

h1 {
text-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
}
Gradient Text:

.gradient-text {
background: linear-gradient(90deg, #ff7e5f, #feb47b);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

21
Clipping Text:

.clipped-text {
background-image: url('pattern.png');
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
Animated Text:

@keyframes typing {
from { width: 0; }
to { width: 100%; }
}
.animated-typing {
overflow: hidden;
white-space: nowrap;
border-right: 2px solid #3498db;
animation: typing 3s steps(40, end), blink-caret 0.75s step-end
infinite;
}
@keyframes blink-caret {
from, to { border-color: transparent; }
50% { border-color: #3498db; }
}

Explanation:

● Text Shadows add depth and emphasis to text.


● Gradient Text creates visually appealing text with color gradients.
● Clipping Text fills text with an image pattern.
● Animated Text simulates typing effects, enhancing interactivity.

7. CSS Architecture
A well-structured CSS architecture ensures scalability, maintainability, and consistency across
large projects. Approaches like BEM, OOCSS, and SMACSS provide methodologies to
organize CSS effectively.

BEM (Block Element Modifier)

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

22
BEM stands for Block, Element, and Modifier. It's a naming convention that enhances clarity
and reusability.

Structure:

● Block: Independent component (e.g., button)


● Element: Part of a block, dependent on the block (e.g., button__icon)
● Modifier: Variation of a block or element (e.g., button--large)

Example:

<button class="btn btn--primary">


<span class="btn__icon"> 🔍</span>
Search
</button>
.btn {
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.btn--primary {
background-color: #3498db;
color: white;
}
.btn__icon {
margin-right: 8px;
}

Benefits:

● Clarity: Clearly identifies relationships between components.


● Reusability: Facilitates the creation of modular and reusable components.
● Maintainability: Simplifies updates and reduces naming conflicts.

OOCSS (Object-Oriented CSS)

OOCSS promotes separation of structure and skin, and separation of container and content,
encouraging reusable and maintainable CSS.

Principles:
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

23
1. Separate Structure and Skin:
○ Structure: Layout-related styles.
○ Skin: Visual styles like colors and fonts.
2. Separate Container and Content:
○ Ensures components are independent of their parent containers.

Example:

<div class="media">
<img class="media__image" src="avatar.jpg" alt="Avatar">
<div class="media__body">
<h4 class="media__heading">John Doe</h4>
<p class="media__text">Lorem ipsum dolor sit amet.</p>
</div>
</div>
.media {
display: flex;
}
.media__image {
width: 64px;
height: 64px;
border-radius: 50%;
margin-right: 15px;
}
.media__body {
flex: 1;
}
.media__heading {
margin: 0;
font-size: 1.2em;
}
.media__text {
margin: 5px 0 0;
color: #7f8c8d;
}

Benefits:

● Reusability: Encourages building components that can be reused in different contexts.


● Maintainability: Simplifies maintenance by promoting clear separation of concerns.
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

24
SMACSS (Scalable and Modular Architecture for CSS)

SMACSS is a style guide that categorizes CSS rules into different types to promote scalability
and maintainability.

Categories:

1. Base: Default styles for HTML elements.


2. Layout: Major structural sections (e.g., header, footer).
3. Module: Reusable components (e.g., cards, nav bars).
4. State: Styles that describe the state of modules or layouts (e.g., hidden, active).
5. Theme: Styles that apply visual themes (e.g., dark mode).

Example:

<div class="layout-header">
<nav class="module-nav module-nav--primary">
<ul>
<li class="module-nav__item"><a href="#">Home</a></li>
<li class="module-nav__item"><a href="#">About</a></li>
<li class="module-nav__item"><a href="#">Contact</a></li>
</ul>
</nav>
</div>
/* Base */
body {
margin: 0;
font-family: Arial, sans-serif;
}
/* Layout */
.layout-header {
background-color: #2c3e50;
padding: 20px;
}
/* Module */
.module-nav {
display: flex;
}
.module-nav__item {
margin-right: 15px;
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

25
}
.module-nav--primary a {
color: white;
text-decoration: none;
}
/* State */
.module-nav--active a {
border-bottom: 2px solid #e74c3c;
}

Benefits:

● Organization: Clearly categorizes CSS rules for better manageability.


● Scalability: Facilitates growth of stylesheets without becoming unmanageable.
● Reusability: Promotes the creation of reusable components and modules.

8. CSS Performance Optimization


Optimizing CSS ensures that your website loads quickly and runs smoothly across all devices.
Efficient CSS practices enhance user experience and improve SEO rankings.

Minimizing Repaints and Reflows

Repaints and Reflows are browser processes that render changes to the DOM. Minimizing
these can significantly boost performance.

Tips:

● Limit Layout Thrashing: Avoid forcing the browser to recalculate styles and layouts
frequently.
○ Example: Batch DOM reads and writes separately.
● Use CSS Transforms and Opacity: These properties do not trigger reflows.

Example:

.animate {
transform: translateX(100px);
opacity: 0.5;
transition: transform 0.3s ease, opacity 0.3s ease;
}

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

26
● Avoid Animating Layout-Affecting Properties: Such as width, height, top, left.
● Use will-change: Hint the browser about upcoming changes.

Example:

.button {
will-change: transform;
}

Optimizing Selectors

Efficient selectors enhance CSS performance by reducing the time the browser spends
matching elements.

Best Practices:

● Start with the Most Specific Selector: This reduces the number of elements the
browser needs to check.

Example:

/* Inefficient */
div ul li a { /* styles */ }
/* Efficient */
.nav-link { /* styles */ }

● Avoid Universal Selectors (*): They match all elements, causing performance issues.
● Limit Use of Descendant Selectors: They require the browser to traverse the DOM.
● Use Class and ID Selectors: These are faster as they map directly to elements.

Example:

/* Inefficient */
div.content p.intro span.highlight {
color: red;
}
/* Efficient */
.highlight {
color: red;
}

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

27
Critical CSS

Critical CSS involves inlining essential CSS required for above-the-fold content, improving
initial page load times.

Steps:

1. Identify Critical CSS: Determine styles necessary for rendering above-the-fold content.
2. Inline Critical CSS: Embed these styles directly within the <head> of the HTML.
3. Load Remaining CSS Asynchronously: Use techniques like media="print" or
JavaScript to load non-critical CSS.

Example:

<head>
<style>
/* Critical CSS */
body { margin: 0; font-family: Arial, sans-serif; }
header { background-color: #2c3e50; padding: 20px; color:
white; }
/* ... other critical styles ... */
</style>
<link rel="stylesheet" href="styles.css" media="print"
onload="this.media='all'">
<noscript><link rel="stylesheet" href="styles.css"></noscript>
</head>

Explanation:

● Critical styles are inlined to ensure immediate rendering.


● Non-critical styles are loaded asynchronously to prevent blocking the initial render.

Using CSS Containment

The contain property isolates a component's styles and layout, preventing them from affecting
or being affected by other parts of the DOM.

Syntax:

.element {
contain: layout style;
}
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

28
Values:

● layout: Contains layout changes within the element.


● style: Contains style changes within the element.
● paint: Contains paint rendering within the element.
● size: Contains size changes within the element.
● strict: Equivalent to layout style paint.

Example:

.card {
contain: layout style;
width: 300px;
padding: 20px;
border: 1px solid #ccc;
}

Benefits:

● Performance: Reduces the scope of CSS and layout recalculations.


● Isolation: Prevents unintended style leaks between components.

9. CSS Houdini
CSS Houdini is a collection of low-level APIs that give developers more control over CSS by
exposing parts of the CSS engine. It enables the creation of custom CSS properties, layout
algorithms, and more.

Introduction to Houdini

Houdini aims to bridge the gap between CSS and JavaScript, allowing developers to write
plugins that extend CSS's capabilities without waiting for browser support.

Key APIs:

● Paint API: Enables custom painting/rendering for elements.


● Layout API: Allows defining custom layout algorithms.
● Animation Worklet: Facilitates custom animations.
● Properties and Values API: Defines new CSS properties with type validation.

Custom Paint API

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

29
The Paint API allows developers to create custom drawings for elements using the Canvas API.

Example:

JavaScript:

if ('paintWorklet' in CSS) {
CSS.paintWorklet.addModule('circle-paint.js');
}

circle-paint.js:

class CirclePainter {
static get inputProperties() { return ['--circle-color',
'--circle-radius']; }
paint(ctx, size, properties) {
const color = properties.get('--circle-color').toString() ||
'blue';
const radius =
parseInt(properties.get('--circle-radius').toString()) || 50;
ctx.beginPath();
ctx.arc(size.width / 2, size.height / 2, radius, 0, 2 *
Math.PI);
ctx.fillStyle = color;
ctx.fill();
}
}
registerPaint('circle', CirclePainter);

CSS:

.box {
width: 200px;
height: 200px;
background-image: paint(circle);
--circle-color: #e74c3c;
--circle-radius: 80px;
}

Explanation:

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

30
● JavaScript: Registers the circle-paint.js module with the Paint Worklet.
● circle-paint.js: Defines a CirclePainter class that draws a circle based on custom
properties.
● CSS: Applies the custom paint to the .box element using background-image:
paint(circle); and sets the custom properties --circle-color and
--circle-radius.

Layout API

The Layout API allows developers to define custom layout algorithms, enabling new layout
patterns beyond existing CSS capabilities.

Example:

Note: As of now, the Layout API is experimental and not widely supported across browsers.

10. CSS for Accessibility


Ensuring that your CSS enhances accessibility is vital for creating inclusive web experiences.
Advanced CSS techniques can improve usability for all users, including those with disabilities.

Ensuring Color Contrast

High contrast between text and background colors improves readability, especially for users with
visual impairments.

Guidelines:

● WCAG Standards: Aim for a contrast ratio of at least 4.5:1 for normal text and 3:1 for
large text.
● Tools: Use tools like WebAIM Contrast Checker to verify contrast ratios.

Example:

/* Sufficient contrast */
.button {
background-color: #2980b9;
color: #ffffff;
}
/* Insufficient contrast */
.button {
background-color: #bdc3c7;
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

31
color: #ecf0f1;
}

Focus States

Visible focus indicators help keyboard users navigate interactive elements.

Best Practices:

● Always Define Focus Styles: Avoid removing or hiding default focus outlines.
● Ensure Visibility: Make focus indicators distinct and noticeable.

Example:

/* Custom focus style */


a:focus, button:focus, input:focus {
outline: 3px dashed #e74c3c;
outline-offset: 2px;
}

Avoiding Motion Sensitivity Issues

Animations can cause discomfort for users with motion sensitivities. Respecting user
preferences enhances accessibility.

Implementation:

@media (prefers-reduced-motion: reduce) {


* {
animation: none !important;
transition: none !important;
}
}

Explanation:

● Detects if the user prefers reduced motion and disables animations and transitions
accordingly.

11. CSS Filters and Blend Modes

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

32
CSS provides powerful visual effects through filters and blend modes, enabling dynamic
image and element manipulation without relying on external graphics software.

Filter Property

The filter property applies graphical effects like blurring, color shifting, and brightness
adjustments to elements.

Common Filter Functions:

● blur(px): Applies a Gaussian blur.


● brightness(%): Adjusts brightness.
● contrast(%): Adjusts contrast.
● grayscale(%): Converts to grayscale.
● sepia(%): Applies a sepia tone.
● invert(%): Inverts colors.
● saturate(%): Adjusts saturation.
● hue-rotate(deg): Rotates hue.

Example:

/* Grayscale on hover */
img:hover {
filter: grayscale(100%);
transition: filter 0.5s ease;
}
/* Brightness adjustment */
.button {
filter: brightness(100%);
transition: filter 0.3s ease;
}
.button:hover {
filter: brightness(120%);
}

Explanation:

● Images turn grayscale when hovered over with a smooth transition.


● Buttons become brighter on hover to indicate interactivity.

Mix-blend-mode and Background-blend-mode


Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

33
Blend Modes determine how an element's content blends with its background or adjacent
elements, creating complex visual effects.

mix-blend-mode

Applies a blend mode between an element and its immediate parent background.

Syntax:

.element {
mix-blend-mode: multiply;
}

Example:

<div class="image-container">
<img src="background.jpg" alt="Background">
<img src="overlay.png" alt="Overlay" class="overlay">
</div>
.image-container {
position: relative;
}
.overlay {
position: absolute;
top: 0;
left: 0;
mix-blend-mode: multiply;
opacity: 0.7;
}

Explanation:

● The .overlay image blends with the .image-container background using the
multiply blend mode, creating a composite effect.

background-blend-mode

Applies a blend mode between multiple background layers of an element.

Example:

.hero {
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

34
background-image: url('background.jpg'), url('overlay.png');
background-blend-mode: overlay;
background-size: cover;
height: 400px;
}

Explanation:

● The two background images blend using the overlay mode, enhancing visual depth
and texture.

12. Best Practices and Common Pitfalls


Best Practices

1. Maintain Consistent Naming Conventions:


○ Use methodologies like BEM, OOCSS, or SMACSS to keep class names
organized and meaningful.

Example:

.card__title { /* styles */ }
.card__body { /* styles */ }
.card--featured { /* styles */ }

2. Leverage CSS Variables for Theming:


○ Define and reuse variables for colors, fonts, and spacing to simplify theme
changes.

Example:

:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
}
.button {
background-color: var(--primary-color);
color: white;
}
.button.secondary {

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

35
background-color: var(--secondary-color);
}

3. Optimize CSS Delivery:


○ Minimize and concatenate CSS files to reduce HTTP requests.
○ Utilize critical CSS and defer non-critical styles.

Example:

<style>
/* Critical CSS */
body { margin: 0; font-family: Arial, sans-serif; }
header { background-color: #2c3e50; padding: 20px; color: white; }
</style>
<link rel="stylesheet" href="styles.css" media="print"
onload="this.media='all'">
<noscript><link rel="stylesheet" href="styles.css"></noscript>

4. Use Shorthand Properties:


○ Simplify CSS by using shorthand properties where applicable.

Example:

/* Longhand */
margin-top: 10px;
margin-right: 15px;
margin-bottom: 10px;
margin-left: 15px;
/* Shorthand */
margin: 10px 15px;

5. Implement Responsive Images:


○ Use srcset and sizes attributes to serve appropriately sized images for
different viewports.

Example:

<img src="small.jpg"
srcset="small.jpg 480w, medium.jpg 800w, large.jpg 1200w"
sizes="(max-width: 600px) 480px, (max-width: 900px) 800px,
1200px"
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

36
alt="Responsive Image">

6. Document Your CSS:


○ Use comments to explain complex sections and maintain readability.

Example:

/* Flex container for navigation links */


.nav {
display: flex;
justify-content: space-between;
}

7. Utilize Preprocessors and Post-processors:


○ Tools like Sass, Less, or PostCSS enhance CSS development with features like
nesting, variables, and autoprefixing.
8. Regularly Audit Your CSS:
○ Remove unused styles to reduce file size and prevent conflicts.
○ Tools: PurgeCSS, UnCSS

Common Pitfalls

1. Overly Specific Selectors:


○ Highly specific selectors can make overriding styles difficult and reduce flexibility.

Avoid:

div.container ul li a.button { /* styles */ }


Prefer:

.button { /* styles */ }

2. Lack of Responsive Design:


○ Ignoring responsiveness can lead to poor user experiences on various devices.
○ Solution: Incorporate media queries and flexible units.
3. Using Inline Styles Excessively:
○ Inline styles hinder maintainability and reuse.
○ Solution: Favor class-based styling.
4. Neglecting Accessibility:
○ Failing to consider accessibility can exclude users with disabilities.
○ Solution: Ensure color contrast, focus states, and respect user preferences.
5. Forgetting Browser Compatibility:
○ Advanced CSS features may not be supported across all browsers.
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

37
○ Solution: Use Can I Use to check compatibility and provide fallbacks.
6. Not Optimizing for Performance:
○ Bloated CSS can slow down page loads.
○ Solution: Minimize CSS, use efficient selectors, and optimize animations.
7. Inconsistent Styling:
○ Lack of consistency leads to a disjointed design.
○ Solution: Establish a design system and adhere to it.
8. Ignoring Semantic HTML:
○ Styling without semantic structure can complicate CSS and accessibility.
○ Solution: Use appropriate HTML elements to convey meaning.
9. Overusing CSS Frameworks:
○ Relying too much on frameworks can result in unnecessary bloat and limit
customization.
○ Solution: Use frameworks judiciously and customize as needed.
10. Not Using Developer Tools Effectively:
○ Failing to utilize browser developer tools can slow down debugging and
optimization.
○ Solution: Familiarize yourself with tools like Chrome DevTools for inspecting and
profiling CSS.

13. Multiple Choice Questions


Test your understanding of Advanced CSS with the following multiple-choice questions.
Answers and explanations are provided after each question.

Question 1

What CSS property is primarily used to define a grid container?

A) display: flex;
B) display: grid;
C) position: grid;
D) grid-template;

Answer: B) display: grid;

Explanation:

● display: grid; establishes an element as a grid container, enabling the use of CSS
Grid Layout properties.

Question 2
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

38
Which of the following selectors targets all <a> elements that have an href attribute
ending with ".pdf"?

A) a[href*=".pdf"]
B) a[href^=".pdf"]
C) a[href$=".pdf"]
D) a[href~=".pdf"]

Answer: C) a[href$=".pdf"]

Explanation:

● The $= operator selects elements with an attribute value ending with the specified string.
Here, it targets <a> elements with href attributes ending in ".pdf".

Question 3

How can you ensure that an animation pauses when a user prefers reduced motion?

A) Remove all animations from the CSS.


B) Use JavaScript to detect user preferences and disable animations.
C) Utilize the prefers-reduced-motion media query to disable animations.
D) It's not possible to respect user preferences for reduced motion.

Answer: C) Utilize the prefers-reduced-motion media query to disable animations.

Explanation:

● The prefers-reduced-motion media query detects if the user has requested


reduced motion, allowing developers to adjust or disable animations accordingly.

Question 4

Which CSS function allows you to constrain a value between a minimum and maximum
range?

A) calc()
B) clamp()
C) var()
D) min()

Answer: B) clamp()

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

39
Explanation:

● The clamp() function restricts a value within a specified minimum and maximum range,
ensuring responsiveness and accessibility.

Question 5

What is the main advantage of using CSS Variables over preprocessor variables (like
Sass variables)?

A) They are processed at compile-time.


B) They can be updated dynamically at runtime.
C) They are not supported in modern browsers.
D) They require less code.

Answer: B) They can be updated dynamically at runtime.

Explanation:

● CSS Variables (Custom Properties) can be manipulated with JavaScript and respond to
changes in the DOM, offering dynamic theming capabilities that preprocessor variables
do not provide.

Question 6

In BEM methodology, what does the double underscore (__) signify in a class name?

A) A block
B) An element
C) A modifier
D) A state

Answer: B) An element

Explanation:

● In BEM, the double underscore (__) separates the block from its element, indicating a
component's part.

Question 7

Which of the following is a benefit of using contain in CSS?

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

40
A) It applies a theme to the element.
B) It isolates the element's styles and layout to improve performance.
C) It defines a grid layout.
D) It adds a shadow to the element.

Answer: B) It isolates the element's styles and layout to improve performance.

Explanation:

● The contain property restricts the scope of an element's styles and layout, preventing
them from affecting or being affected by other parts of the DOM, thereby enhancing
performance.

Question 8

What does the @media rule with min-width: 768px typically target?

A) Mobile devices
B) Tablets and above
C) Desktops only
D) Printers

Answer: B) Tablets and above

Explanation:

● A min-width of 768px generally targets tablet-sized screens and larger devices,


applying responsive styles accordingly.

Question 9

Which CSS function would you use to create a responsive font size that scales between a
minimum and maximum value based on viewport width?

A) calc()
B) clamp()
C) var()
D) max()

Answer: B) clamp()

Explanation:

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

41
● clamp() allows setting a font size that scales responsively within defined minimum and
maximum values, ensuring readability across devices.

Question 10

What does the grid-template-areas property do in CSS Grid Layout?

A) Defines the number of columns and rows.


B) Specifies the size of each grid cell.
C) Assigns names to grid areas for easier placement of grid items.
D) Sets the gap between grid items.

Answer: C) Assigns names to grid areas for easier placement of grid items.

Explanation:

● grid-template-areas allows developers to define named areas within the grid,


simplifying the placement of grid items using grid-area.

Question 11

Which of the following properties can be animated without triggering reflows or repaints,
ensuring better performance?

A) width
B) height
C) transform
D) left

Answer: C) transform

Explanation:

● Animating transform is hardware-accelerated and does not trigger layout changes,


making it more performance-friendly compared to properties like width or left.

Question 12

In Flexbox, which property aligns items along the cross axis?

A) justify-content
B) align-items

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

42
C) flex-direction
D) flex-wrap

Answer: B) align-items

Explanation:

● align-items aligns flex items along the cross axis, which is perpendicular to the main
axis defined by flex-direction.

Question 13

What is the purpose of the @keyframes rule in CSS Animations?

A) To define the duration of an animation.


B) To specify the key points and styles in an animation sequence.
C) To apply transformations to elements.
D) To set the iteration count of an animation.

Answer: B) To specify the key points and styles in an animation sequence.

Explanation:

● @keyframes defines the intermediate steps and styles that occur at various points
during an animation, allowing for complex motion effects.

Question 14

Which of the following is NOT a valid value for the animation-fill-mode property?

A) none
B) forwards
C) backwards
D) center

Answer: D) center

Explanation:

● center is not a valid value for animation-fill-mode. Valid values include none,
forwards, backwards, and both.

Question 15
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

43
What does the grid-auto-flow property control in CSS Grid Layout?

A) The size of the grid tracks.


B) The direction in which auto-placed items are inserted into the grid.
C) The gap between grid items.
D) The alignment of grid items.

Answer: B) The direction in which auto-placed items are inserted into the grid.

Explanation:

● grid-auto-flow determines how auto-placed grid items are positioned within the grid,
such as row-wise or column-wise.

14. Exercises
Enhance your understanding of Advanced CSS by completing the following exercises. Each
exercise is designed to reinforce key concepts and provide hands-on experience.

Exercise 1: Create a Responsive Grid Layout

Objective: Design a responsive grid layout that adjusts the number of columns based on the
viewport width using CSS Grid.

Tasks:

HTML Structure:

<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>
CSS Styling:

.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

44
grid-gap: 20px;
padding: 20px;
}
.grid-item {
background-color: #2ecc71;
color: white;
font-size: 2em;
display: flex;
align-items: center;
justify-content: center;
height: 150px;
border-radius: 8px;
}

Expected Outcome:

A grid that displays as many columns as fit within the viewport, each grid item maintaining a
minimum width of 150px and adjusting responsively as the screen size changes.

Exercise 2: Implement CSS Variables for Theming

Objective: Use CSS Variables to create a light and dark theme switcher.

Tasks:

HTML Structure:

<button id="themeToggle">Toggle Theme</button>


<div class="content">
<h1>Welcome to My Website</h1>
<p>This is a sample paragraph to demonstrate theming with CSS
Variables.</p>
</div>
CSS Styling:

:root {
--background-color: #ffffff;
--text-color: #000000;
--primary-color: #3498db;
}
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

45
.dark-theme {
--background-color: #2c3e50;
--text-color: #ecf0f1;
--primary-color: #e74c3c;
}
body {
background-color: var(--background-color);
color: var(--text-color);
transition: background-color 0.3s ease, color 0.3s ease;
}
.content {
padding: 20px;
}
button {
background-color: var(--primary-color);
color: white;
border: none;
padding: 10px 20px;
cursor: pointer;
border-radius: 4px;
}
button:hover {
opacity: 0.8;
}
JavaScript:

const themeToggle = document.getElementById('themeToggle');


themeToggle.addEventListener('click', () => {
document.documentElement.classList.toggle('dark-theme');
});

Expected Outcome:

Clicking the "Toggle Theme" button switches between light and dark themes by updating CSS
Variables, altering background and text colors dynamically with smooth transitions.

Exercise 3: Build an Accessible Navigation Menu

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

46
Objective: Create a navigation menu that is accessible, featuring keyboard navigation and
visible focus states.

Tasks:

HTML Structure:

<nav class="nav">
<ul>
<li><a href="#" class="nav-link">Home</a></li>
<li><a href="#" class="nav-link">About</a></li>
<li><a href="#" class="nav-link">Services</a></li>
<li><a href="#" class="nav-link">Contact</a></li>
</ul>
</nav>
CSS Styling:

.nav {
background-color: #34495e;
padding: 10px 20px;
}
.nav ul {
list-style: none;
display: flex;
justify-content: space-around;
margin: 0;
padding: 0;
}
.nav-link {
color: #ecf0f1;
text-decoration: none;
padding: 8px 16px;
border-radius: 4px;
transition: background-color 0.3s ease;
}
.nav-link:hover,
.nav-link:focus {
background-color: #2ecc71;
outline: none;
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

47
}
/* Visible focus state */
.nav-link:focus {
box-shadow: 0 0 0 3px rgba(46, 204, 113, 0.5);
}

Explanation:

● Keyboard Navigation: Ensures that links can be focused using the Tab key.
● Visible Focus States: Provides a clear visual indicator when a link is focused,
enhancing usability for keyboard users.
● Accessible Colors: Maintains sufficient color contrast between text and background.

Expected Outcome:

An accessible navigation menu where links are easily navigable via keyboard, with distinct
hover and focus styles ensuring visibility and interactivity.

Exercise 4: Create a Custom Checkbox with CSS

Objective: Design a custom-styled checkbox that replaces the default browser appearance,
enhancing aesthetics while maintaining accessibility.

Tasks:

HTML Structure:

<label class="custom-checkbox">
<input type="checkbox">
<span class="checkmark"></span>
Accept Terms and Conditions
</label>
CSS Styling:

/* Hide the default checkbox */


.custom-checkbox input {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

48
}
/* Create a custom checkmark */
.checkmark {
position: relative;
height: 20px;
width: 20px;
background-color: #eee;
border-radius: 4px;
display: inline-block;
margin-right: 10px;
vertical-align: middle;
transition: background-color 0.3s ease;
}
/* When the checkbox is checked */
.custom-checkbox input:checked ~ .checkmark {
background-color: #2ecc71;
}
/* Add a checkmark symbol */
.checkmark::after {
content: "";
position: absolute;
display: none;
}
/* Show the checkmark when checked */
.custom-checkbox input:checked ~ .checkmark::after {
display: block;
}
/* Style the checkmark */
.custom-checkbox .checkmark::after {
left: 7px;
top: 3px;
width: 5px;
height: 10px;
border: solid white;
border-width: 0 2px 2px 0;
transform: rotate(45deg);
}

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

49
/* Hover effect */
.custom-checkbox:hover input ~ .checkmark {
background-color: #ccc;
}

Explanation:

● Hiding Default Checkbox: The actual <input> is hidden to allow custom styling.
● Custom Checkmark: The .checkmark span visually represents the checkbox.
● Checked State: When the checkbox is checked, the background color changes, and a
white checkmark appears.
● Accessibility: The label ensures that clicking the custom checkbox toggles the input
state, maintaining accessibility.

Expected Outcome:

A visually appealing custom checkbox that changes color and displays a checkmark when
selected, enhancing the user interface while preserving functionality and accessibility.

Exercise 5: Develop a Responsive Typography System

Objective: Create a responsive typography system using CSS Variables and clamp() to
ensure text scales appropriately across different screen sizes.

Tasks:

HTML Structure:

<div class="typography-demo">
<h1 class="heading">Responsive Heading</h1>
<p class="paragraph">This is a responsive paragraph that adjusts
its font size based on the viewport width.</p>
</div>
CSS Styling:

:root {
--font-size-base: 16px;
--font-size-heading: clamp(2rem, 5vw, 3rem);
--font-size-paragraph: clamp(1rem, 2.5vw, 1.5rem);
--line-height-base: 1.5;
}

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

50
body {
font-size: var(--font-size-base);
line-height: var(--line-height-base);
font-family: 'Helvetica Neue', Arial, sans-serif;
padding: 20px;
}
.heading {
font-size: var(--font-size-heading);
margin-bottom: 10px;
}
.paragraph {
font-size: var(--font-size-paragraph);
}

Explanation:

● CSS Variables: Define base font sizes and line heights for consistency.
● clamp() Function: Ensures font sizes stay within a specified range while scaling with
viewport width.
● Responsive Typography: Text adjusts fluidly between minimum and maximum sizes
based on screen width.

Expected Outcome:

A typography system where headings and paragraphs scale responsively, maintaining


readability and aesthetic appeal across various devices and screen sizes.

15. Conclusion
Congratulations! You've completed the comprehensive guide to Advanced CSS. This guide has
provided you with in-depth knowledge of sophisticated CSS techniques, enabling you to create
dynamic, responsive, and maintainable web designs. By mastering these advanced concepts,
you can enhance the visual appeal, performance, and accessibility of your websites, ensuring a
superior user experience.

Next Steps

1. Implement Advanced Techniques: Start incorporating CSS Grid, Flexbox, Variables,


and other advanced features into your projects.
2. Explore CSS Houdini: Dive deeper into cutting-edge CSS APIs to unlock new styling
possibilities.
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

51
3. Stay Updated: CSS evolves continuously. Follow reputable sources and communities to
stay informed about the latest advancements.
4. Optimize for Performance: Regularly audit and refine your CSS to maintain optimal
performance and efficiency.
5. Enhance Accessibility: Prioritize accessible design practices to create inclusive web
experiences.
6. Engage with the Community: Share your work, seek feedback, and collaborate with
other developers to further hone your skills.

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

52

You might also like