Module 1: Introduction to CSS
What is CSS?
CSS (Cascading Style Sheets) is a style sheet language used for describing the presentation of a document written in HTML or XML. It controls the layout and appearance of web pages, making them visually appealing and user-friendly.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: lightblue;
}
</style>
</head>
<body>
<h1>Welcome to CSS</h1>
<p>CSS styles this page!</p>
</body>
</html>
Purpose of CSS
Separation of Content and Design: Keeps HTML focused on structure while CSS handles design.
Consistency: Ensures uniform styling across multiple web pages.
Improved Accessibility: Makes websites more accessible by adapting styles to different devices and screen sizes.
Example:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Global Styling Example</h1>
<p>This paragraph inherits styles from an external CSS file.</p>
</body>
</html>
/* styles.css */
body {
font-family: Arial, sans-serif;
color: darkslategray;
}
h1 {
text-align: center;
color: teal;
}
Advantages of Using CSS
Saves Time: Reuse styles across multiple pages.
Improved Website Speed: Allows for smaller HTML files by separating design and structure.
Better Maintainability: Simplifies updating styles.
Device Adaptability: Creates responsive designs for different screen sizes.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: coral;
font-size: 2em;
}
p {
line-height: 1.5;
}
</style>
</head>
<body>
<h1>CSS Advantages</h1>
<p>Using CSS makes development efficient and consistent.</p>
</body>
</html>
Types of CSS
Inline CSS
Internal CSS
External CSS
Inline CSS
Inline CSS applies styles directly within an HTML tag.
Syntax:
<tag style="property: value;">Content</tag>
Example:
<!DOCTYPE html>
<html>
<body>
<h1 style="color: blue; text-align: center;">Inline CSS Example</h1>
<p style="font-size: 20px;">This paragraph uses inline CSS.</p>
</body>
</html>
Internal CSS
Internal CSS is defined within a <style> tag in the <head> section of an HTML document.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: lavender;
}
h1 {
color: darkblue;
text-transform: uppercase;
}
</style>
</head>
<body>
<h1>Internal CSS Example</h1>
<p>This page uses internal CSS.</p>
</body>
</html>
External CSS
External CSS is stored in an external file and linked using the <link> tag.
Example:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>External CSS Example</h1>
<p>This paragraph inherits styles from an external file.</p>
</body>
</html>
/* styles.css */
body {
background-color: beige;
font-family: Verdana, sans-serif;
}
h1 {
color: navy;
border-bottom: 2px solid gray;
}
CSS Syntax
Structure:
selector {
property: value;
}
Selector: Targets the HTML element.
Declaration Block: Enclosed in curly braces, containing:
Property: Attribute to style (e.g., color, font-size).
Value: Value assigned to the property.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: maroon;
font-weight: bold;
}
</style>
</head>
<body>
<p>CSS Syntax Example</p>
</body>
</html>
Selectors
CSS selectors specify which elements to style.
Type Selector: Targets elements by tag name.
Class Selector: Targets elements with a specific class.
ID Selector: Targets elements with a specific ID.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: green;
}
.highlight {
background-color: yellow;
}
#unique {
font-style: italic;
}
</style>
</head>
<body>
<p>This is a type selector example.</p>
<p class="highlight">This is a class selector example.</p>
<p id="unique">This is an ID selector example.</p>
</body>
</html>
Declaration Block (Property and Value)
A declaration block defines the properties and values for styling.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
text-align: center;
color: crimson;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>Property and Value Example</h1>
</body>
</html>
Module 2: CSS Basics
Selectors
Selectors are patterns used to select and style specific HTML elements.
Universal Selector (*)
Selects all elements on a page.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<h1>Universal Selector Example</h1>
<p>All elements have no margin or padding.</p>
</body>
</html>
Type Selector (e.g., p)
Selects all elements of a specific type.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: navy;
font-size: 16px;
}
</style>
</head>
<body>
<p>This is a paragraph styled with a type selector.</p>
</body>
</html>
Class Selector (.class)
Selects elements with a specific class attribute.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<p class="highlight">This paragraph is highlighted.</p>
</body>
</html>
ID Selector (#id)
Selects a single element with a specific ID.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
#unique {
font-size: 20px;
color: crimson;
}
</style>
</head>
<body>
<p id="unique">This paragraph uses an ID selector.</p>
</body>
</html>
Grouping Selectors
Styles multiple elements with the same declaration.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, p {
color: teal;
}
</style>
</head>
<body>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<p>Paragraph</p>
</body>
</html>
Colors and Backgrounds
Color Formats
Named Colors: e.g., red, blue.
HEX: e.g., #ff5733.
RGB: e.g., rgb(255, 87, 51).
HSL: e.g., hsl(9, 100%, 60%).
Example:
<!DOCTYPE html>
<html>
<head>
<style>
.named {
color: red;
}
.hex {
color: #ff5733;
}
.rgb {
color: rgb(255, 87, 51);
}
.hsl {
color: hsl(9, 100%, 60%);
}
</style>
</head>
<body>
<p class="named">Named color example.</p>
<p class="hex">HEX color example.</p>
<p class="rgb">RGB color example.</p>
<p class="hsl">HSL color example.</p>
</body>
</html>
Background Properties
Background Color: Sets background color.
Background Image: Sets an image as the background.
Background Position: Positions the background image.
Background Repeat: Repeats or prevents repetition.
Background Size: Sets background image size.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: lightblue;
background-image: url('example.jpg');
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
</style>
</head>
<body>
<h1>Background Properties Example</h1>
</body>
</html>
Typography
Font Properties
Font Family: Specifies font type.
Font Size: Sets font size.
Font Weight: Defines thickness (e.g., bold).
Font Style: Specifies style (e.g., italic).
Font Variant: Sets variant (e.g., small-caps).
Example:
<!DOCTYPE html>
<html>
<head>
<style>
p {
font-family: Arial, sans-serif;
font-size: 18px;
font-weight: bold;
font-style: italic;
font-variant: small-caps;
}
</style>
</head>
<body>
<p>Typography Example</p>
</body>
</html>
Line Height, Letter Spacing, and Word Spacing
Line Height: Adjusts space between lines.
Letter Spacing: Adjusts space between letters.
Word Spacing: Adjusts space between words.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
p {
line-height: 1.8;
letter-spacing: 2px;
word-spacing: 5px;
}
</style>
</head>
<body>
<p>Line height, letter spacing, and word spacing example.</p>
</body>
</html>
Text Alignment, Decoration, and Transformation
Text Alignment: Aligns text (e.g., left, right, center).
Text Decoration: Adds decoration (e.g., underline, line-through).
Text Transformation: Converts text (e.g., uppercase, lowercase).
Example:
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
text-align: center;
}
p {
text-decoration: underline;
text-transform: uppercase;
}
</style>
</head>
<body>
<h1>Text Alignment Example</h1>
<p>Text Decoration and Transformation Example</p>
</body>
</html>
Module 3: CSS Box Model
Understanding the Box Model
The CSS Box Model describes how elements are structured on a web page. Each element is treated as a rectangular box consisting of the following components:
Content: The actual content inside the box (e.g., text or an image).
Padding: Space between the content and the border.
Border: A line surrounding the padding and content.
Margin: Space between the element and its surroundings.
Diagram:
+-------------------+
| Margin |
| +-------------+ |
| | Border | |
| | +---------+ | |
| | | Padding | | |
| | | Content | | |
| | +---------+ | |
| +-------------+ |
+-------------------+
Example:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 300px;
padding: 20px;
border: 5px solid black;
margin: 10px;
background-color: lightblue;
}
</style>
</head>
<body>
<div>Box Model Example</div>
</body>
</html>
Content
The content is the innermost part of the box, where text or images reside.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 200px;
height: 100px;
background-color: lightgray;
}
</style>
</head>
<body>
<div>This is the content area.</div>
</body>
</html>
Padding
Padding is the space between the content and the border. It increases the size of the box without affecting the margin.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
div {
padding: 30px;
background-color: lightcoral;
}
</style>
</head>
<body>
<div>Padding Example</div>
</body>
</html>
Border
The border is a line surrounding the content and padding.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 5px solid navy;
padding: 10px;
}
</style>
</head>
<body>
<div>Border Example</div>
</body>
</html>
Margin
Margin is the space between the element and other elements. It is completely transparent and does not affect the size of the box.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
div {
margin: 20px;
background-color: lightgreen;
padding: 10px;
}
</style>
</head>
<body>
<div>Margin Example</div>
</body>
</html>
Width and Height
Defines the size of the content area. The total size of an element is:
Total Width = Width + Padding (left & right) + Border (left & right) + Margin (left & right)
Total Height = Height + Padding (top & bottom) + Border (top & bottom) + Margin (top & bottom)
Example:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 200px;
height: 100px;
border: 2px solid black;
padding: 10px;
margin: 20px;
background-color: lightyellow;
}
</style>
</head>
<body>
<div>Width and Height Example</div>
</body>
</html>
Fixed, Percentage, and Auto Values
Fixed Values: Specified in units like px or em.
Percentage Values: Relative to the parent element.
Auto: Automatically adjusts based on content and parent element.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
.fixed {
width: 200px;
height: 100px;
background-color: lightblue;
}
.percentage {
width: 50%;
height: 50px;
background-color: lightpink;
}
.auto {
width: auto;
height: 100px;
background-color: lightgray;
}
</style>
</head>
<body>
<div class="fixed">Fixed Width</div>
<div class="percentage">50% Width</div>
<div class="auto">Auto Width</div>
</body>
</html>
Min/Max-Width and Min/Max-Height
Min-Width/Min-Height: Ensures a minimum size.
Max-Width/Max-Height: Limits the maximum size.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 80%;
min-width: 300px;
max-width: 600px;
height: auto;
background-color: lightgoldenrodyellow;
}
</style>
</head>
<body>
<div>Resize the browser to see min/max width in action.</div>
</body>
</html>
Module 4: CSS Layouts
Positioning
CSS provides various positioning methods to control the layout of elements on the page. Understanding these methods is essential for creating dynamic and interactive web designs.
1. Static Positioning (default)
Elements are positioned according to the normal document flow (from top to bottom). By default, all elements have position: static, and no positioning properties (like top, right, bottom, left) can be used with them.
css
div {
position: static; /* Default positioning */
}
2. Relative Positioning
An element with position: relative is positioned relative to its normal position. You can move it using the top, right, bottom, or left properties without affecting the layout of other elements.
css
div {
position: relative;
top: 20px; /* Moves the element 20px down */
left: 30px; /* Moves the element 30px to the right */
}
3. Absolute Positioning
An element with position: absolute is positioned relative to the nearest positioned ancestor (an element that has position: relative, absolute, or fixed). If no such ancestor exists, it is positioned relative to the <html> element.
css
div {
position: absolute;
top: 10px;
left: 10px;
}
4. Fixed Positioning
An element with position: fixed is positioned relative to the viewport, meaning it stays in the same position even when the page is scrolled.
css
div {
position: fixed;
top: 0;
right: 0;
}
Z-index
The z-index property specifies the stack order of elements. Elements with a higher z-index will appear in front of elements with a lower z-index.
css
div {
position: absolute;
z-index: 10; /* Higher value means the element will be on top */
}
Display and Visibility
1. Display Property
The display property determines how an element is displayed on the page.
Block: Takes up the full width available and starts on a new line.
css
div {
display: block;
}
Inline: Does not start on a new line and only takes up as much width as necessary.
css
span {
display: inline;
}
Inline-block: Behaves like an inline element but allows you to set width and height.
css
div {
display: inline-block;
}
None: The element is not displayed and does not take up any space.
css
div {
display: none;
}
2. Visibility Property
The visibility property controls the visibility of an element, but unlike display: none, the element still takes up space on the page.
Visible: The element is visible.
css
div {
visibility: visible;
}
Hidden: The element is hidden but still occupies space in the layout.
css
div {
visibility: hidden;
}
Flexbox
Flexbox is a layout model that allows you to design complex layouts with ease and responsiveness.
1. Flex Container Properties
To create a flex container, you set the display property to flex.
css
.container {
display: flex;
}
2. Aligning Items
justify-content: Aligns items horizontally along the main axis (default is left to right).
css
.container {
justify-content: center; /* Centers items horizontally */
}
align-items: Aligns items vertically along the cross axis.
css
.container {
align-items: center; /* Centers items vertically */
}
align-self: Allows individual flex items to override the align-items setting.
css
.item {
align-self: flex-start; /* Aligns this item to the start */
}
3. Flex Growth, Shrinkage, and Basis
flex-grow: Defines the ability for a flex item to grow if necessary.
flex-shrink: Defines the ability for a flex item to shrink if necessary.
flex-basis: Specifies the initial size of the flex item before any growing or shrinking.
css
.item {
flex-grow: 1; /* The item will grow to fill available space */
flex-shrink: 1; /* The item can shrink if necessary */
flex-basis: 100px; /* The item starts with a width of 100px */
}
CSS Grid
CSS Grid is a two-dimensional layout system that allows you to design both rows and columns.
1. Grid Container and Grid Items
To define a grid, set the parent container's display property to grid. The children of the grid container become grid items.
css
.container {
display: grid;
}
2. Defining Rows and Columns
You define rows and columns using grid-template-rows and grid-template-columns. You can specify fixed sizes or use flexible units like fr (fractional units).
css
.container {
grid-template-rows: 100px 200px; /* Two rows with specific heights */
grid-template-columns: 1fr 2fr; /* Two columns with flexible widths */
}
3. Grid Template Areas
grid-template-areas allows you to define a grid layout using names for specific areas.
css
.container {
grid-template-areas:
"header header"
"main sidebar"
"footer footer";
}
.item-header {
grid-area: header;
}
.item-main {
grid-area: main;
}
.item-sidebar {
grid-area: sidebar;
}
.item-footer {
grid-area: footer;
}
HTML Example: Combining Flexbox and Grid
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Layouts</title>
<style>
/* Flexbox Example */
.flex-container {
display: flex;
justify-content: space-between;
align-items: center;
}
.flex-item {
flex-grow: 1;
text-align: center;
}
/* Grid Example */
.grid-container {
display: grid;
grid-template-columns: 1fr 2fr;
grid-template-rows: auto;
grid-template-areas:
"header header"
"main sidebar"
"footer footer";
}
.header {
grid-area: header;
background-color: #f1f1f1;
padding: 10px;
}
.main {
grid-area: main;
background-color: #c1c1c1;
padding: 10px;
}
.sidebar {
grid-area: sidebar;
background-color: #e1e1e1;
padding: 10px;
}
.footer {
grid-area: footer;
background-color: #d1d1d1;
padding: 10px;
}
</style>
</head>
<body>
<!-- Flexbox Example -->
<div class="flex-container">
<div class="flex-item">Item 1</div>
<div class="flex-item">Item 2</div>
<div class="flex-item">Item 3</div>
</div>
<!-- Grid Example -->
<div class="grid-container">
<div class="header">Header</div>
<div class="main">Main Content</div>
<div class="sidebar">Sidebar</div>
<div class="footer">Footer</div>
</div>
</body>
</html>
Styling Links, Lists, and Tables
Styling Links
Links are styled using various pseudo-classes and properties to create visual effects when interacting with them.
1. Pseudo-classes for Links
:link: Styles links that have not yet been clicked.
:visited: Styles links that the user has already clicked.
:hover: Styles links when the user hovers the mouse pointer over them.
:active: Styles links when the user clicks on them.
css
a:link {
color: blue; /* Color of unvisited link */
text-decoration: none; /* Remove underline */
}
a:visited {
color: purple; /* Color of visited link */
}
a:hover {
color: red; /* Color when hovered */
text-decoration: underline; /* Add underline on hover */
}
a:active {
color: green; /* Color when link is clicked */
}
You can also combine these pseudo-classes to apply a specific style:
css
a {
color: blue; /* Default link color */
text-decoration: none; /* Remove underline */
}
a:hover, a:focus {
color: red; /* Change color on hover/focus */
text-decoration: underline;
}
Styling Lists
CSS provides several ways to style ordered and unordered lists. You can customize the appearance of list items, their bullet points, and their numbering.
1. List-style Properties
list-style-type: Defines the bullet or number style for list items.
css
ul {
list-style-type: square; /* Use a square bullet point */
}
ol {
list-style-type: upper-roman; /* Roman numerals */
}
Common values for list-style-type:
disc (default for unordered lists)
circle
square
decimal (default for ordered lists)
lower-roman, upper-roman
none (removes bullet points)
list-style-position: Determines the position of the list marker (bullet or number).
css
ul {
list-style-position: inside; /* Marker inside the list item */
}
ol {
list-style-position: outside; /* Marker outside the list item */
}
list-style-image: Allows you to use an image as the list marker.
css
ul {
list-style-image: url('bullet.png'); /* Custom image for bullets */
}
list-style: A shorthand property to set list-style-type, list-style-position, and list-style-image at once.
css
ul {
list-style: circle inside; /* Circle bullet inside the list item */
}
Styling Tables
Tables can be styled to improve readability and design. CSS properties can be used to control table borders, spacing, alignment, and more.
1. Border-collapse and Border-spacing
border-collapse: Specifies whether table borders should collapse into a single border or be separated.
css
table {
border-collapse: collapse; /* Collapses borders */
}
th, td {
border: 1px solid black; /* Adds border to table cells */
}
border-spacing: Specifies the distance between table cells.
css
table {
border-spacing: 10px; /* Adds space between table cells */
}
2. Table Alignment
You can align the content of table cells using text-align for horizontal alignment and vertical-align for vertical alignment.
css
th, td {
text-align: center; /* Centers text horizontally */
vertical-align: middle; /* Centers text vertically */
}
3. Styling Table Headers
Table headers can be styled separately using the th selector to differentiate them from other table cells.
css
th {
background-color: #f2f2f2; /* Light gray background */
font-weight: bold; /* Make text bold */
text-align: left; /* Align text to the left */
}
4. Zebra Striping for Tables
You can use alternating row colors for better readability (zebra striping).
css
tr:nth-child(even) {
background-color: #f9f9f9; /* Light gray background for even rows */
}
tr:nth-child(odd) {
background-color: #ffffff; /* White background for odd rows */
}
5. Adding Padding to Table Cells
You can add padding to table cells to create spacing between the content and the cell borders.
css
th, td {
padding: 10px; /* Adds 10px padding around the content */
}
Example: Complete Styling for Links, Lists, and Tables
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Styled Links, Lists, and Tables</title>
<style>
/* Styling Links */
a:link {
color: blue;
text-decoration: none;
}
a:visited {
color: purple;
}
a:hover {
color: red;
text-decoration: underline;
}
a:active {
color: green;
}
/* Styling Lists */
ul {
list-style-type: square;
list-style-position: inside;
}
ol {
list-style-type: upper-roman;
}
/* Styling Tables */
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 10px;
border: 1px solid black;
text-align: center;
}
th {
background-color: #f2f2f2;
font-weight: bold;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
tr:nth-child(odd) {
background-color: #ffffff;
}
</style>
</head>
<body>
<!-- Links Section -->
<h2>Styled Links</h2>
<a href="#">Visit Our Website</a>
<!-- Lists Section -->
<h2>Styled Lists</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<ol>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ol>
<!-- Tables Section -->
<h2>Styled Table</h2>
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
<tr>
<td>Alice</td>
<td>25</td>
<td>USA</td>
</tr>
<tr>
<td>Bob</td>
<td>30</td>
<td>UK</td>
</tr>
<tr>
<td>Charlie</td>
<td>35</td>
<td>Canada</td>
</tr>
</table>
</body>
</html>
Module 6: Advanced Selectors and Pseudo-elements
In CSS, advanced selectors and pseudo-elements offer more control over element selection and styling. They allow you to target elements in more complex ways, beyond simple element, class, or ID selectors.
Attribute Selectors
Attribute selectors allow you to target elements based on the presence and value of their attributes.
1. [attribute]
Targets elements that have the specified attribute, regardless of its value.
css
/* Selects all elements with a "type" attribute */
input[type] {
background-color: lightblue;
}
2. [attribute=value]
Targets elements with the specified attribute that has an exact value.
css
/* Selects all <a> elements with an href attribute equal to "example.com" */
a[href="example.com"] {
color: red;
}
3. [attribute^=value]
Targets elements whose attribute value starts with a specified value.
css
/* Selects all <a> elements where the href attribute starts with "https" */
a[href^="https"] {
color: green;
}
4. [attribute$=value]
Targets elements whose attribute value ends with a specified value.
css
/* Selects all <a> elements with an href attribute ending with ".html" */
a[href$=".html"] {
color: blue;
}
5. [attribute*=value]
Targets elements whose attribute value contains the specified value.
css
/* Selects all <a> elements with an href attribute containing the word "example" */
a[href*="example"] {
color: purple;
}
Combinators
Combinators are used to define relationships between selectors and target elements based on their position relative to others.
1. Descendant Combinator (space)
The descendant combinator (space) selects elements that are descendants of another element (any level of nesting).
css
/* Selects all <p> elements that are inside a <div> */
div p {
color: blue;
}
2. Child Combinator (>)
The child combinator (>) selects elements that are direct children of another element (one level of nesting).
css
/* Selects all <li> elements that are direct children of <ul> */
ul > li {
list-style-type: square;
}
3. Adjacent Sibling Combinator (+)
The adjacent sibling combinator (+) selects an element that is immediately preceded by a specific element.
css
/* Selects the <p> element that comes directly after a <h2> */
h2 + p {
font-style: italic;
}
4. General Sibling Combinator (~)
The general sibling combinator (~) selects all sibling elements that follow a specific element, regardless of whether they are immediately adjacent.
css
/* Selects all <p> elements that come after a <h2> */
h2 ~ p {
color: gray;
}
Pseudo-elements
Pseudo-elements are used to style specific parts of an element, such as its before or after content.
1. ::before
The ::before pseudo-element allows you to insert content before an element’s actual content.
css
/* Adds content before each <h2> element */
h2::before {
content: "➤ "; /* Inserts a bullet point before the heading */
font-size: 1.5em;
}
2. ::after
The ::after pseudo-element allows you to insert content after an element’s actual content.
css
/* Adds content after each <h2> element */
h2::after {
content: " ✔"; /* Adds a checkmark after the heading */
color: green;
}
content Property: The content property is required for pseudo-elements ::before and ::after to display the inserted content.
css
/* Example using the content property */
p::before {
content: "Note: "; /* Adds "Note: " before the paragraph */
font-weight: bold;
}
Advanced Pseudo-classes
Pseudo-classes are used to apply styles to elements based on their state or position.
1. :nth-child(n)
The :nth-child() pseudo-class allows you to target elements based on their position within a parent element, using a number or formula.
css
/* Selects every 2nd <li> element */
li:nth-child(2n) {
background-color: lightgray;
}
/* Selects the 3rd <li> element */
li:nth-child(3) {
color: red;
}
2. :first-child
The :first-child pseudo-class selects the first child element within a parent.
css
/* Selects the first <p> element inside each <div> */
div p:first-child {
font-weight: bold;
}
3. :last-child
The :last-child pseudo-class selects the last child element within a parent.
css
/* Selects the last <p> element inside each <div> */
div p:last-child {
margin-bottom: 0;
}
4. :first-of-type
The :first-of-type pseudo-class selects the first element of its type (tag) within a parent, regardless of its position in the document.
css
/* Selects the first <p> element inside each <div> */
div p:first-of-type {
color: blue;
}
5. :last-of-type
The :last-of-type pseudo-class selects the last element of its type within a parent.
css
/* Selects the last <p> element inside each <div> */
div p:last-of-type {
color: green;
}
6. :not(selector)
The :not() pseudo-class allows you to select all elements that do not match a specific selector.
css
/* Selects all <p> elements except those with the class "highlight" */
p:not(.highlight) {
color: gray;
}
Example: Combining Advanced Selectors and Pseudo-elements
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Selectors and Pseudo-elements</title>
<style>
/* Attribute Selector */
a[href^="https"] {
color: green;
}
/* Combinators */
div > p {
color: blue;
}
h2 + p {
font-weight: bold;
}
/* Pseudo-elements */
p::before {
content: "Note: ";
font-weight: bold;
}
/* Advanced Pseudo-classes */
li:nth-child(odd) {
background-color: lightgray;
}
li:first-of-type {
color: red;
}
/* Styling with :not() */
p:not(.highlight) {
color: gray;
}
</style>
</head>
<body>
<a href="https://example.com">Example Link</a>
<div>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</div>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<p class="highlight">This paragraph is highlighted.</p>
<p>This paragraph is not highlighted.</p>
</body>
</html>
This example demonstrates the use of attribute selectors, combinators, pseudo-elements (::before, ::after), and advanced pseudo-classes (:nth-child, :first-of-type, :not()). You can see how these selectors provide more granular control over the appearance and behavior of elements on a page.
Module 7: Responsive Design
Responsive design is a fundamental concept in modern web development, allowing websites to adapt to various screen sizes and devices. This module focuses on media queries, responsive typography, and viewport units, as well as understanding different CSS units.
Media Queries
Media queries are used to apply styles based on specific conditions, such as the width of the viewport. They enable you to create designs that work across different screen sizes and devices.
Syntax
Media queries are written with the @media rule and can include conditions like width, height, and orientation.
css
/* Example of media query for screens larger than 768px (tablet) */
@media (min-width: 768px) {
body {
background-color: lightblue;
}
}
/* Example of media query for screens smaller than 480px (mobile) */
@media (max-width: 480px) {
body {
background-color: lightpink;
}
}
Breakpoints
Breakpoints are specific screen widths where the layout of your website should change to improve usability and readability. Common breakpoints include:
Mobile devices: max-width: 480px
Tablets: min-width: 481px to max-width: 768px
Laptops/desktops: min-width: 769px
A typical responsive design would include multiple breakpoints to ensure a seamless user experience across devices.
css
/* Mobile */
@media (max-width: 480px) {
body {
font-size: 14px;
}
}
/* Tablet */
@media (min-width: 481px) and (max-width: 768px) {
body {
font-size: 16px;
}
}
/* Desktop */
@media (min-width: 769px) {
body {
font-size: 18px;
}
}
Responsive Typography
Responsive typography ensures text remains legible and proportionate across different screen sizes. It can be achieved using relative units like em, rem, or vw.
1. Using em and rem for Relative Font Size
em: Relative to the font size of the parent element.
rem: Relative to the root element (<html>), typically used for consistency across the website.
css
/* Base font size */
html {
font-size: 16px; /* 1rem = 16px */
}
/* Responsive font size */
h1 {
font-size: 2rem; /* 2 * 16px = 32px */
}
p {
font-size: 1.2em; /* 1.2 times the parent font size */
}
2. Using Viewport Width (vw) for Font Size
You can also use viewport units (vw, vh, vmin, vmax) for responsive typography.
css
h1 {
font-size: 8vw; /* 8% of the viewport width */
}
This ensures the text size scales with the width of the viewport.
Viewport Units
Viewport units allow for responsive designs that scale based on the dimensions of the browser window. They can be very useful for fluid layouts.
1. vh (Viewport Height)
1 vh is equal to 1% of the height of the viewport.
css
div {
height: 50vh; /* 50% of the viewport height */
}
2. vw (Viewport Width)
1 vw is equal to 1% of the width of the viewport.
css
div {
width: 80vw; /* 80% of the viewport width */
}
3. vmin and vmax
vmin: The smaller of vw and vh.
vmax: The larger of vw and vh.
css
div {
width: 50vmin; /* 50% of the smaller viewport dimension */
}
h1 {
font-size: 5vmax; /* 5% of the larger viewport dimension */
}
These units make it easier to create fluid and responsive designs that adapt to both width and height.
CSS Units
CSS offers both relative and absolute units. Understanding the difference between these can help you make your designs more flexible and adaptable.
1. Relative Units
em: Relative to the font-size of the parent element. Useful for scalable layouts and typography.
rem: Relative to the root (html) element's font-size. Provides consistency across the site.
%: Relative to the parent element's size, often used for width, height, and margins.
css
/* Example of using rem and em */
html {
font-size: 16px; /* 1rem = 16px */
}
div {
width: 50%; /* 50% of the parent element's width */
}
p {
font-size: 1.5em; /* 1.5 times the parent font size */
}
2. Absolute Units
px (pixels): Fixed size, does not scale with screen size. Useful for precise control over design elements.
cm (centimeters), mm (millimeters): Physical units based on real-world measurements, but they are not commonly used in web design due to differences in screen resolution.
css
/* Example of using px for fixed size */
div {
width: 200px; /* Fixed width of 200px */
}
p {
margin-top: 10px; /* Fixed margin of 10px */
}
While absolute units (like px) give you precise control over the design, relative units (like em, rem, %) make your design more flexible and adaptable to various screen sizes and user preferences.
Example: Responsive Design with Media Queries, Viewport Units, and Typography
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Design Example</title>
<style>
/* Base Styles */
html {
font-size: 16px; /* 1rem = 16px */
}
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
h1 {
font-size: 6vw; /* Responsive font size */
}
p {
font-size: 1.2rem;
margin: 20px;
}
/* Mobile (max-width: 480px) */
@media (max-width: 480px) {
h1 {
font-size: 8vw;
}
p {
font-size: 1rem;
}
}
/* Tablet (min-width: 481px and max-width: 768px) */
@media (min-width: 481px) and (max-width: 768px) {
h1 {
font-size: 7vw;
}
p {
font-size: 1.1rem;
}
}
/* Desktop (min-width: 769px) */
@media (min-width: 769px) {
h1 {
font-size: 4vw;
}
p {
font-size: 1.2rem;
}
}
</style>
</head>
<body>
<h1>Responsive Design</h1>
<p>This paragraph will adjust its font size based on the screen width. Resize the browser window to see the effect.</p>
</body>
</html>
This example demonstrates how to create a responsive design with flexible font sizes using viewport units (vw) and relative units (rem). The layout adapts to different screen sizes using media queries and adjusts the typography accordingly.
Summary
Media Queries: Essential for creating responsive layouts by applying styles based on screen size, width, and other properties.
Responsive Typography: Achieved using units like em, rem, and vw, making text size scalable for different devices.
Viewport Units: vh, vw, vmin, and vmax allow design elements to scale relative to the viewport size.
CSS Units: Relative units like em and % are flexible, while absolute units like px give precise control over sizes.
Module 8: CSS Transitions and Animations
CSS transitions and animations provide the ability to create dynamic visual effects, enhancing user experience with smooth animations and interactive elements. This module focuses on transitions, animations, and transformations.
CSS Transitions
A transition in CSS allows you to change property values smoothly over a specified duration, providing a natural and attractive effect. Transitions are typically triggered by user interactions like hovering or focusing on an element.
Transition Properties
transition-property: Specifies the CSS property that should be transitioned (e.g., background-color, width, etc.).
transition-duration: Defines the time over which the transition should occur (e.g., 1s, 500ms).
transition-timing-function: Controls the pacing of the transition. Common values are linear, ease, ease-in, ease-out, and cubic-bezier().
transition-delay: Specifies the delay before the transition begins.
Syntax
css
/* Example of a transition */
.element {
background-color: red;
transition-property: background-color;
transition-duration: 0.5s;
transition-timing-function: ease-in-out;
transition-delay: 0s;
}
.element:hover {
background-color: blue; /* Change on hover */
}
In the above example:
When .element is hovered, the background-color changes from red to blue over a half-second duration.
The transition is smooth due to the ease-in-out timing function.
Example: Transition on Hover
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Transition Example</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: lightgreen;
transition: transform 0.3s ease, background-color 0.5s ease-in-out;
}
.box:hover {
background-color: coral;
transform: rotate(45deg);
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
In this example, the .box element transitions its background color and rotates when hovered.
CSS Animations
CSS animations allow for more complex and continuous animations. Unlike transitions, animations do not require a user interaction and can run automatically or be triggered by events like hovering.
@keyframes
The @keyframes rule defines the keyframes of an animation, specifying how the properties should change over time. It allows you to create animations by setting the starting and ending states, and intermediate steps.
css
@keyframes example {
0% {
transform: rotate(0deg);
background-color: lightblue;
}
50% {
transform: rotate(180deg);
background-color: coral;
}
100% {
transform: rotate(360deg);
background-color: lightblue;
}
}
The above @keyframes rule defines an animation that rotates an element 360 degrees while changing its background color.
Animation Properties
animation-name: Specifies the name of the @keyframes animation.
animation-duration: Defines how long the animation will take.
animation-timing-function: Specifies how the intermediate keyframes are calculated (e.g., ease, linear, cubic-bezier).
animation-delay: Delays the start of the animation.
animation-iteration-count: Specifies how many times the animation should run (e.g., infinite for endless looping).
animation-direction: Specifies whether the animation should run in reverse or alternate between forwards and backward.
Syntax
css
/* Applying an animation */
.element {
animation-name: example; /* Name of the animation */
animation-duration: 3s; /* Duration of 3 seconds */
animation-timing-function: ease-in-out; /* Smooth easing */
animation-iteration-count: infinite; /* Infinite loop */
}
Example: Rotating Box Animation
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Animation Example</title>
<style>
@keyframes rotateBox {
0% {
transform: rotate(0deg);
background-color: lightblue;
}
100% {
transform: rotate(360deg);
background-color: coral;
}
}
.box {
width: 200px;
height: 200px;
background-color: lightblue;
animation: rotateBox 5s infinite ease-in-out;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
In this example, the .box element continuously rotates and changes color using a keyframe animation.
Transformations
CSS transformations allow you to modify the position, size, and shape of elements, including rotating, scaling, skewing, and translating.
1. rotate
Rotates an element around a fixed point (default is the center of the element).
css
/* Rotate 45 degrees */
.element {
transform: rotate(45deg);
}
2. scale
Scales an element's size by a specified factor.
css
/* Scale element to 1.5 times its original size */
.element {
transform: scale(1.5);
}
3. skew
Skews an element by a specified degree along the X and/or Y axis.
css
/* Skew element by 20 degrees on the X-axis */
.element {
transform: skewX(20deg);
}
4. translate
Moves an element from its current position based on specified values.
css
/* Move the element 50px to the right and 30px down */
.element {
transform: translate(50px, 30px);
}
Combining Transformations
You can combine multiple transformations by separating them with spaces.
css
.element {
transform: rotate(45deg) scale(1.2) translate(50px, 20px);
}
Example: Box with Multiple Transformations
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Transform Example</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: lightblue;
transition: transform 0.5s ease-in-out;
}
.box:hover {
transform: rotate(45deg) scale(1.2) translate(50px, 30px);
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
In this example, the .box element rotates, scales, and moves when hovered.
Summary
Transitions: Smoothly change property values over a specified duration with options for timing functions, delays, and multiple properties.
Animations: Create more complex and continuous animations using @keyframes with properties like animation-name, duration, and iteration-count.
Transformations: Use rotate, scale, skew, and translate to modify the position, size, and appearance of elements.
Module 9: CSS Variables and Functions
CSS Variables and Functions are powerful tools that improve code reusability, maintainability, and flexibility. This module covers how to define and use CSS variables, and introduces CSS functions like calc(), clamp(), and gradients such as linear-gradient and radial-gradient.
CSS Variables
CSS Variables, also known as Custom Properties, allow you to define reusable values that can be referenced throughout your CSS. They help avoid repetitive code and make it easier to maintain and update your styles.
Declaring CSS Variables
CSS variables are declared inside a selector (typically :root for global use) with a -- prefix followed by the variable name. You can then assign values to the variables.
css
/* Declaring CSS variables */
:root {
--primary-color: #3498db;
--font-size: 16px;
--padding: 20px;
}
In the example above, three CSS variables are declared in the :root scope, making them available globally across the document.
Using CSS Variables
Once a CSS variable is declared, it can be accessed using the var() function. You can use it in any property where a value is expected.
css
/* Using CSS variables */
body {
font-size: var(--font-size);
padding: var(--padding);
background-color: var(--primary-color);
}
This makes it easy to change the --primary-color, --font-size, or --padding globally by modifying the values in one place (in the :root selector).
CSS Variables with Fallbacks
You can provide fallback values in case a variable is not defined or supported in certain browsers.
css
/* Using a fallback value */
body {
background-color: var(--background-color, #f0f0f0); /* Fallback to #f0f0f0 */
}
CSS Functions
CSS functions allow for dynamic property values, enabling calculations, measurements, and creative effects.
1. calc() Function
The calc() function performs calculations to determine CSS property values. It can combine units (e.g., px, em, %, vw, etc.).
css
/* Example of using calc() */
div {
width: calc(100% - 20px); /* 100% of the container's width minus 20px */
padding: calc(10px + 2vw); /* Padding will adjust based on viewport width */
}
calc() is useful when you need to create responsive layouts or precise positioning.
2. clamp() Function
The clamp() function allows you to set a CSS value that adjusts between a defined minimum, preferred, and maximum value.
css
/* Example of using clamp() */
h1 {
font-size: clamp(16px, 5vw, 36px); /* Font size will be between 16px and 36px, depending on the viewport width */
}
In this example, the font size of h1 will be at least 16px, but will grow with the viewport width up to a maximum of 36px.
3. Gradients
Gradients are a way of creating smooth transitions between multiple colors in CSS. They are often used as backgrounds or other visual effects.
Linear Gradient: Gradients that transition from one color to another in a straight line.
css
/* Example of linear-gradient */
div {
background: linear-gradient(to right, red, yellow, green);
height: 200px;
width: 100%;
}
This creates a gradient that smoothly transitions from red to yellow to green horizontally.
Radial Gradient: Gradients that transition from the center outwards in a circular or elliptical pattern.
css
/* Example of radial-gradient */
div {
background: radial-gradient(circle, blue, green, yellow);
height: 200px;
width: 100%;
}
This creates a gradient that starts from the center (blue) and radiates outward (green, then yellow).
Example: Using CSS Variables, calc(), and Gradients
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Variables and Functions Example</title>
<style>
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--font-size: 16px;
--container-padding: 20px;
}
body {
font-size: var(--font-size);
background-color: var(--primary-color);
color: white;
margin: 0;
}
.container {
padding: var(--container-padding);
background: linear-gradient(to right, var(--primary-color), var(--secondary-color));
width: calc(100% - 40px); /* Full width minus padding */
height: 200px;
}
h1 {
font-size: clamp(20px, 5vw, 36px); /* Responsive font size */
text-align: center;
line-height: 200px; /* Vertically centers the text */
}
</style>
</head>
<body>
<div class="container">
<h1>Responsive Heading</h1>
</div>
</body>
</html>
In this example:
CSS variables are used to define reusable colors, font size, and padding.
calc() is used to set the container width to 100% - 40px, accounting for padding.
clamp() is used to make the font size of the heading responsive based on viewport width.
Linear gradient is applied as the background of the .container.
Summary
CSS Variables: Allow you to define reusable values (e.g., colors, font sizes) and make your code more maintainable and adaptable.
CSS Functions:
calc(): Performs calculations for CSS property values.
clamp(): Sets a value that adjusts between a minimum, preferred, and maximum value based on conditions like viewport size.
Gradients: Creates smooth transitions between colors, useful for background images and other visual effects.
Comments
Post a Comment
If you have any Doubts plz let me know