Css
Css
Table of Contents
Chapter 1: Introduction to CSS
Chapter 2: CSS Selectors
Chapter 3: Styling Text and Fonts
Chapter 4: Box Model in CSS
Chapter 5: CSS Layout Techniques
Chapter 6: CSS Colors and Backgrounds
Chapter 7: CSS Transitions and Animations
Chapter 8: Responsive Design with CSS
Chapter 9: CSS Flexbox
Chapter 10: CSS Grid Layout
Chapter 11: CSS Typography and Web Fonts
Chapter 12: CSS Pseudo-classes and Pseudo-elements
Chapter 13: CSS Variables (Custom Properties)
Chapter 14: Advanced CSS Selectors
Chapter 15: CSS Media Queries
Chapter 16: Advanced Layouts with Flexbox and Grid
Chapter 17: CSS Preprocessors (Sass, LESS)
Chapter 18: Advanced Animations and Keyframes
Chapter 19: CSS Transforms and 3D Transforms
Chapter 20: CSS Filters and Effects
Chapter 21: CSS Techniques for Web Performance
Chapter 22: Debugging and Browser Compatibility in CSS
Chapter 23: Advanced CSS Concepts and Best Practices
Chapter 24: CSS for Mobile-first and Accessibility
History of CSS
CSS was first introduced by Håkon Wium Lie in 1994. At that time, HTML
was primarily used for structuring content, and there was limited ability to
control the visual presentation of web pages. CSS allowed web developers
to separate the structure of the webpage (HTML) from the design, making
websites more flexible and maintainable.
Over the years, CSS has undergone significant evolution, with new features
and specifications being introduced to handle the increasing complexity of
modern websites. CSS 2.0, released in 1998, was a major update, adding
more sophisticated layout and positioning tools. Later, CSS3 introduced
modules like Flexbox, Grid, and animation support, further expanding the
power of CSS.
What is CSS?
CSS stands for Cascading Style Sheets, and it is the language used to style
HTML documents. By using CSS, you can control the visual appearance of
web pages, defining how elements such as text, images, and layouts are
displayed on different devices and screen sizes.
Colors: CSS allows you to define colors for text, background, borders,
and more.
Typography: You can define font styles, sizes, and alignments.
Spacing: Control the margins, padding, and spacing between elements.
Layout: Organize elements using Flexbox, Grid, and positioning
techniques.
Responsive Design: Make websites responsive using media queries for
various screen sizes.
CSS Syntax
CSS is composed of selectors and declaration blocks. The selector targets
HTML elements, and the declaration block contains properties and values
that define the style.
Types of CSS
CSS can be applied to HTML documents in three main ways: Inline CSS,
Internal CSS, and External CSS.
Type of
Description Example
CSS
CSS defined directly within an
Inline <h1 style="color:
HTML element using the `style`
CSS blue;">Hello World</h1>
attribute.
CSS written inside the <style> tag
Internal <style> h1 color: blue;
in the <head> section of an HTML
CSS </style>
document.
CSS contained in an external file
External <link rel="stylesheet"
linked to the HTML document
CSS href="styles.css">
using the <link> tag.
CSS Selectors
CSS selectors are used to target specific HTML elements to apply styles.
Here are some common types of selectors:
Element Selector: Targets elements by their name (e.g., `h1`, `p`, `div`).
Class Selector: Targets elements with a specific class attribute (e.g.,
`.class-name`).
ID Selector: Targets an element with a specific ID (e.g., `#id-name`).
Attribute Selector: Targets elements with a specific attribute (e.g.,
`[type="text"]`).
CSS follows a system called the "cascade," which determines the order in
which styles are applied. If two rules conflict, the more specific rule takes
precedence. This system makes it easy to manage styles in complex
websites.
Basic Selectors
At the core of CSS are the basic selectors: Element selectors, Class
selectors, and ID selectors. These are the most commonly used selectors,
and mastering them is essential for writing clean, maintainable CSS.
/* Element Selector */
h1 {
color: blue;
}
/* Class Selector */
.button {
background-color: red;
padding: 10px 20px;
font-size: 16px;
border-radius: 5px;
transition: background-color 0.3s ease;
}
/* ID Selector */
#header {
font-size: 24px;
text-align: center;
margin-bottom: 20px;
}
Grouping Selectors
Grouping selectors allows you to apply the same styles to multiple elements
at once. This technique makes your CSS more efficient and reduces
repetition in your code. It’s especially useful when you need to apply similar
styles to various elements across your layout.
Descendant Selectors
Descendant selectors allow you to target elements that are nested within
other elements. This selector is useful when you want to style child elements
based on their position in the DOM hierarchy, without being too specific.
/* Descendant selector */
.container p {
font-size: 18px;
color: #666;
line-height: 1.6;
}
Child Selectors
Child selectors target only direct children of an element, excluding deeper
nested elements. This selector provides more control over which elements
are selected, and helps avoid unwanted cascading styles.
/* Child selector */
ul > li {
font-weight: bold;
font-size: 20px;
color: darkblue;
}
Pseudo-Classes
Pseudo-classes target elements in specific states, such as when they are
being hovered over, focused on, or active. These selectors are essential for
adding interactivity and visual feedback to elements without JavaScript.
Example: Pseudo-Classes
/* Pseudo-class example */
a:hover {
color: red;
text-decoration: underline;
}
Pseudo-Elements
Pseudo-elements allow you to style specific parts of an element. They’re
particularly useful for adding decorative elements like icons, content before
or after elements, or modifying text properties.
Example: Pseudo-Elements
/* Pseudo-elements example */
h2::before {
content: "Chapter ";
font-weight: bold;
}
h2::after {
content: " - Read More!";
color: #ff6347;
}
Attribute Selectors
Attribute selectors target elements based on their attributes, such as the
`href` of links, the `type` of input fields, or the `alt` text of images. They offer
precise control over how elements are selected and styled.
input[type="text"] {
border: 1px solid #ccc;
padding: 10px;
width: 100%;
}
img[alt*="logo"] {
max-width: 200px;
height: auto;
}
Chapter 3: Styling Text and Fonts
Typography is one of the most crucial aspects of web design. Proper text
styling not only enhances readability but also adds personality and helps
communicate the brand’s identity. In this chapter, we will explore the key
CSS properties used for styling text and fonts. You'll learn how to manipulate
text sizes, line heights, font families, weights, and more to create an elegant,
readable design.
/* Styling headings */
h1, h2, h3, h4, h5, h6 {
font-family: 'Roboto', sans-serif;
font-weight: bold;
color: #222;
margin-bottom: 10px;
}
Font Family
The `font-family` property in CSS is used to specify the typeface of your
text. It’s important to pick appropriate fonts for your project to ensure
readability and maintain consistency in branding. Web-safe fonts or custom
web fonts like Google Fonts can be used to ensure text renders correctly
across different devices and browsers.
/* Fallback fonts */
h2 {
font-family: 'Open Sans', Arial, sans-serif;
}
/* Font Size */
p {
font-size: 18px;
}
/* Line Height */
h1 {
font-size: 36px;
line-height: 1.2; /* Tighter line height for headings */
}
p {
font-size: 16px;
line-height: 1.8; /* More spacing for better readability */
}
Font Weight
The `font-weight` property controls the thickness of the text. It can be
specified as a numeric value (from 100 to 900) or as keywords like `normal`,
`bold`, and `bolder`. Adjusting the font weight helps in creating emphasis or
making specific elements stand out in a design.
/* Font weight */
p {
font-weight: normal;
}
strong {
font-weight: bold;
}
h2 {
font-weight: 300;
}
Text Transform
The `text-transform` property is used to control the capitalization of text. It
can be useful when you want to change the case of text without modifying
the underlying HTML content.
/* Text Transform */
h1 {
text-transform: uppercase;
}
h2 {
text-transform: lowercase;
}
button {
text-transform: capitalize;
}
Text Decoration
The `text-decoration` property allows you to add or remove decorations from
text, such as underlines, overlines, or line-through. You can also control the
style and color of these decorations.
/* Text Decoration */
a {
text-decoration: none; /* Removes underline from links */
}
a:hover {
text-decoration: underline;
}
p.strike {
text-decoration: line-through;
color: red;
}
Text Alignment
The `text-align` property defines the alignment of text within an element. The
most common values are `left`, `right`, `center`, and `justify`.
/* Text Alignment */
h1 {
text-align: center;
}
p {
text-align: justify;
}
Content Area
The content area is the innermost part of the box. It is where the actual
content of the element (text, images, etc.) is displayed. The width and height
of the content area are set using the `width` and `height` properties.
Padding
Padding is the space between the content and the border. It helps create
breathing room inside the element, ensuring that the content doesn’t touch
the border. Padding can be set individually for each side of the box (top,
right, bottom, left) using the properties `padding-top`, `padding-right`,
`padding-bottom`, and `padding-left`. You can also use the shorthand
`padding` to apply values for all four sides.
Example: Padding
/* Padding Example */
div {
padding: 20px;
background-color: #e0e0e0;
}
div.custom-padding {
padding-top: 10px;
padding-right: 30px;
padding-bottom: 20px;
padding-left: 5px;
}
This div has padding around the content.
Border
The border surrounds the padding (if defined) and content area. You can
define its width, style, and color using the `border-width`, `border-style`, and
`border-color` properties. The shorthand `border` property can be used to
set all three properties in one go.
Example: Border
/* Border Example */
div {
border: 5px solid black;
padding: 20px;
background-color: #f9f9f9;
}
Margin
Margin is the outermost space that separates the element from its
surroundings. It’s useful for spacing out elements in the layout. Just like
padding, margin can be set for each side individually using the properties
`margin-top`, `margin-right`, `margin-bottom`, and `margin-left`. The
shorthand `margin` property allows you to set all four margins at once.
Example: Margin
/* Margin Example */
div {
margin: 30px;
padding: 20px;
background-color: #e0e0e0;
}
This div has margin around it, creating space between other elements.
Flexbox Layout
Flexbox (Flexible Box) is a CSS layout model that allows you to create
complex layouts with ease, even when the size of the elements is dynamic or
unknown. Flexbox enables the distribution of space inside a container and
aligns items both horizontally and vertically.
Example: Flexbox Layout
.item {
width: 30%;
background-color: #e0e0e0;
padding: 20px;
text-align: center;
}
.item {
background-color: #e0e0e0;
padding: 20px;
text-align: center;
}
Item 1 Item 2 Item 3
Multi-Column Layout
The multi-column layout is perfect for creating newspaper-style columns
where content can flow from one column to another. You can define the
number of columns and space between them using the `column-count` and
`column-gap` properties.
.item {
background-color: #e0e0e0;
margin-bottom: 20px;
padding: 10px;
}
Item 1 Item 2 Item 3
Color Properties
CSS allows you to define colors for text, backgrounds, borders, and other
elements. Colors can be specified in multiple ways, including by name,
hexadecimal values, RGB, RGBA, HSL, and HSLA. Each method provides
flexibility for designing your website's color scheme.
.text-secondary {
color: rgba(46, 204, 113, 0.8); /* RGBA color */
}
.text-accent {
color: hsl(120, 100%, 25%); /* HSL color */
}
Background Properties
CSS provides several ways to style the background of elements, including
background color, images, gradients, and more. The background property
allows you to set these values to create visually striking designs.
.gradient-background {
background: linear-gradient(to right, #ff7e5f, #feb47b); /* Gradient background */
}
Transparent Backgrounds
Using transparency in CSS backgrounds allows you to create layered effects,
where elements can blend with the background behind them. The `rgba()`
and `hsla()` color functions are particularly useful for setting transparent
colors.
.overlay-background {
background-color: hsla(0, 0%, 0%, 0.6); /* Transparent black background */
}
This container has a semi-transparent background.
CSS Transitions
CSS transitions allow you to change property values smoothly over a given
duration when an element's state changes (such as when hovering over it).
Transitions are often used for hover effects, focus states, and other visual
changes that need to be smooth and visually appealing.
.button:hover {
background-color: #2ecc71; /* New background color on hover */
transform: scale(1.1); /* Slightly scale the button */
}
CSS Animations
CSS animations allow you to create complex sequences of movements,
changes, and effects on elements. Unlike transitions, which only animate
from one state to another, animations can define keyframes and iterate
multiple times, offering a higher level of control over the animation flow.
.animated-button {
background-color: #f39c12;
color: white;
padding: 10px 20px;
border-radius: 5px;
animation: bounce 1s ease infinite; /* Apply the bounce animation */
}
/* Combined Example */
.button {
background-color: #3498db;
color: white;
padding: 10px 20px;
border-radius: 5px;
transition: background-color 0.3s ease, transform 0.3s ease; /* Transition property
animation: bounce 1s ease infinite; /* Continuous animation */
}
.button:hover {
background-color: #2ecc71; /* Change background on hover */
transform: scale(1.1); /* Scale up on hover */
}
@keyframes bounce {
0% {
transform: translateY(0);
}
50% {
transform: translateY(-10px);
}
100% {
transform: translateY(0);
}
}
This button has both a transition on hover and a continuous bounce animation.
Media Queries
Media queries are the backbone of responsive design. They allow you to
apply different styles depending on the characteristics of the device or
viewport. By using media queries, you can specify different styles for
different screen sizes, orientations, and device capabilities.
.box {
width: 30%;
margin: 10px;
padding: 20px;
background-color: lightgray;
display: inline-block;
box-sizing: border-box;
}
.item {
flex: 1;
margin: 10px;
padding: 20px;
background-color: lightyellow;
}
.item {
background-color: lightgreen;
padding: 20px;
}
Flexbox Basics
Flexbox is designed to distribute space along a single axis (either
horizontally or vertically). The container becomes a flex container, and its
children (the flex items) can be aligned and spaced in various ways.
.item {
width: 30%;
padding: 20px;
background-color: lightcoral;
text-align: center;
}
Item 1Item 2Item 3
Item 1
Item 2
Item 3
Flex Item Properties
Flex items also have several properties that allow you to control their size,
alignment, and how they grow or shrink inside the flex container. These
properties make it easy to create dynamic and responsive layouts.
.item {
flex-grow: 1; /* Allow the item to grow */
flex-shrink: 1; /* Allow the item to shrink */
flex-basis: 200px; /* Set the initial size */
margin: 10px;
padding: 20px;
background-color: lightblue;
}
Item 1Item 2Item 3
Flexbox Alignment
Flexbox provides powerful alignment tools to align both the items and the
container. You can align items horizontally (along the main axis) or vertically
(along the cross axis).
.item {
width: 100px;
height: 100px;
background-color: lightgreen;
}
Item 1
Advanced Flexbox Layouts
Flexbox can be combined with other CSS properties to create advanced
layouts. For example, using Flexbox with `wrap`, `order`, and `align-self`
allows you to create more complex and dynamic layouts, such as equal-
height columns or responsive grids.
.item {
flex: 1 1 200px; /* Allow items to grow, shrink, and set a base size */
margin: 10px;
padding: 20px;
background-color: lightyellow;
text-align: center;
}
.item:nth-child(odd) {
order: 1; /* Change the order of items */
}
Grid Basics
CSS Grid is based on the concept of a container with rows and columns. The
grid container defines how the space is divided, and the grid items are
placed inside these cells. The container defines the grid structure, and the
items are automatically placed into the grid, but you can also place them
manually for more control.
.item {
background-color: lightcoral;
padding: 20px;
text-align: center;
}
.item {
background-color: lightgreen;
padding: 20px;
text-align: center;
}
Item 1 Item 2 Item 3
Advanced Grid Layouts
CSS Grid Layout allows for more advanced features, such as creating
responsive layouts using media queries, controlling the placement of items
across both rows and columns, and spanning multiple rows or columns.
.item {
background-color: lightyellow;
padding: 20px;
text-align: center;
}
.item:nth-child(1) {
grid-column: span 2; /* Make this item span 2 columns */
}
.item:nth-child(4) {
grid-row: span 2; /* Make this item span 2 rows */
}
Item 1 Item 2 Item 3 Item 4 Item 5 Item 6
Chapter 11: CSS Typography and
Web Fonts
Typography plays a crucial role in the design and readability of a website.
CSS provides powerful tools to control the presentation of text, including
font styles, sizes, weights, line heights, and letter spacing. Additionally, web
fonts enable you to use custom fonts that are not limited to the default
system fonts, allowing for unique and creative designs.
p {
font-family: 'Georgia', serif;
font-size: 18px;
line-height: 1.5;
text-align: justify;
}
ul {
font-family: 'Verdana', sans-serif;
letter-spacing: 0.5px;
font-size: 14px;
}
Heading 1
This is a paragraph styled with a serif font family, a larger font size, and line
spacing for improved readability.
Item 1
Item 2
Item 3
Web Fonts
Web fonts allow you to use custom fonts that are not available by default in a
user's system. By linking to web font providers like Google Fonts, you can
easily import fonts and apply them to your content. This gives you more
flexibility and creativity in your typography.
body {
font-family: 'Roboto', sans-serif;
font-weight: 400;
}
h1 {
font-family: 'Roboto', sans-serif;
font-weight: 700;
}
Font Sizing
Font sizing allows you to set how large or small the text appears. Using
relative units like `em`, `rem`, and percentages offers more flexibility,
especially when designing responsive layouts.
p {
font-size: 1rem; /* 1 root font size */
}
small {
font-size: 0.875rem; /* 0.875 of the root font size */
}
p {
font-weight: 400; /* Normal weight */
font-style: normal; /* Normal style */
}
p {
line-height: 1.7;
letter-spacing: 1px;
}
CSS Pseudo-classes
A pseudo-class is used to define the special state of an element. It can
target states such as when an element is hovered over, focused, or selected.
Some common pseudo-classes include `:hover`, `:focus`, `:active`, `:nth-
child()`, and `:first-child`.
button:focus {
outline: 3px solid #3498db; /* Add outline when focused */
}
li:nth-child(odd) {
background-color: #f2f2f2; /* Odd items have different background */
}
Hover over this link to change color Focus on this button
Item 1
Item 2
Item 3
Item 4
CSS Pseudo-elements
A pseudo-element allows you to style a specific part of an element. Common
pseudo-elements include `::before`, `::after`, `::first-letter`, and `::first-line`.
These pseudo-elements can be used to insert content, style the first letter of
a text, or apply styling to the first line of a paragraph.
div::after {
content: ' (Read more)';
color: #3498db;
}
h2::before {
content: '🔥 ';
color: red;
}
button:focus::before {
content: '🔍 ';
color: #3498db;
}
button {
color: var(--secondary-color);
background-color: var(--primary-color);
padding: 10px 20px;
border: none;
border-radius: 5px;
}
body {
background-color: var(--global-color);
}
.card {
background-color: var(--card-color);
padding: 20px;
border-radius: 10px;
}
Click the button above to dynamically change the background color using CSS
Variables.
Attribute Selectors
Attribute selectors allow you to target elements based on their attributes and
values. You can use different patterns to match attributes, such as exact
match, partial match, and more.
Sample
Pseudo-classes
Pseudo-classes allow you to target elements based on their state or position,
such as when they are hovered, focused, or selected. These selectors are
powerful for interactive designs.
Example: Pseudo-classes
/* Hover effect */
button:hover {
background-color: #3498db;
color: #fff;
}
/* Focus effect */
input:focus {
border-color: #3498db;
outline: none;
}
/* First child */
ul li:first-child {
font-weight: bold;
}
/* Nth-child (even) */
ul li:nth-child(even) {
background-color: #f2f2f2;
}
Item 1
Item 2
Item 3
Pseudo-elements
Pseudo-elements allow you to style specific parts of an element, such as the
first letter, first line, or content inserted before or after an element. These are
useful for adding decorative effects without needing additional HTML.
Example: Pseudo-elements
/* Before pseudo-element */
a::before {
content: "🔗 ";
margin-right: 8px;
}
/* After pseudo-element */
a::after {
content: " (link)";
color: #3498db;
}
Example link
Combinators
Combinators allow you to combine multiple selectors to target elements
based on their relationships in the HTML structure. The four primary
combinators are descendant, child, adjacent sibling, and general sibling.
Example: Combinators
/* Descendant selector */
div p {
color: #3498db;
}
/* Child selector */
ul > li {
list-style-type: square;
}
/* Adjacent sibling */
h1 + p {
margin-top: 0;
}
/* General sibling */
h1 ~ p {
font-style: italic;
}
Main Heading
Paragraph 1
Paragraph 2
Item 1
Item 2
Item 3
Resize the window to see the background color change based on the
viewport width.
/* Mobile devices */
@media (max-width: 480px) {
body {
font-size: 14px;
}
}
/* Tablets */
@media (max-width: 768px) {
body {
font-size: 16px;
}
}
/* Desktops */
@media (min-width: 1024px) {
body {
font-size: 18px;
}
}
Resize the window to see the font size change based on the viewport width.
/* Portrait orientation */
@media (orientation: portrait) {
body {
background-color: lightblue;
}
}
/* Landscape orientation */
@media (orientation: landscape) {
body {
background-color: lightgreen;
}
}
/* High-resolution displays */
@media (min-resolution: 192dpi) {
body {
background-color: lightpink;
}
}
Rotate your device to see the background color change based on the
orientation (portrait or landscape).
/* Apply styles for devices that are 768px wide or less AND in portrait mode */
@media (max-width: 768px) and (orientation: portrait) {
body {
font-size: 14px;
}
}
Resize or rotate the window to see how combining media queries works.
sidebar {
grid-area: sidebar;
background-color: #f0f0f0;
padding: 20px;
}
main {
grid-area: main;
background-color: #f0f0f0;
padding: 20px;
}
footer {
grid-area: footer;
background-color: #f0f0f0;
padding: 20px;
}
/* Responsive layout for smaller screens */
@media (max-width: 768px) {
.container {
grid-template-columns: 1fr;
grid-template-areas:
"header"
"main"
"sidebar"
"footer";
}
}
.footer {
grid-template-columns: 1fr;
}
}
Item 1 Item 2
Footer Footer Footer
1 2 3
Item 3
Chapter 17: CSS Preprocessors
(Sass, LESS)
CSS preprocessors like Sass and LESS allow for more powerful, dynamic,
and maintainable stylesheets. By introducing variables, nesting, mixins, and
other features, preprocessors help to improve code organization and make
stylesheets easier to manage. In this chapter, we will explore the basics of
Sass and LESS, their features, and how to integrate them into your workflow.
Introduction to Sass
Sass (Syntactically Awesome Style Sheets) is one of the most popular CSS
preprocessors. It extends CSS with powerful features such as variables,
nesting, mixins, and inheritance. Let's take a look at how these features can
help improve your styling workflow.
h1 {
color: $secondary-color;
}
.container {
display: flex;
justify-content: space-between;
padding: 20px;
.box {
background-color: darken($primary-color, 10%);
padding: 15px;
border-radius: 5px;
}
}
}
Box 1 Box 2
Introduction to LESS
LESS is another widely used CSS preprocessor that shares many features
with Sass, such as variables, mixins, and nesting. LESS, however, uses a
more CSS-like syntax. It's a great choice for developers who prefer a simpler
approach while still enjoying the benefits of preprocessors.
Example: LESS with Variables and Nesting
h1 {
color: @secondary-color;
}
.container {
display: flex;
justify-content: space-between;
padding: 20px;
.box {
background-color: darken(@primary-color, 10%);
padding: 15px;
border-radius: 5px;
}
}
}
Box 1 Box 2
Variables: Both Sass and LESS allow you to store values (like colors, fonts, or any
CSS value) in variables, which can be reused throughout the stylesheet. This
improves maintainability and reduces repetition.
Nesting: Both preprocessors allow you to nest CSS selectors in a hierarchical
manner, making the structure of your stylesheets more readable and easier to
manage.
Mixins: Sass and LESS offer mixins, which are reusable pieces of code that can
be included in other selectors to avoid code duplication.
Functions and Operations: Both preprocessors support mathematical operations
and functions like color manipulation (e.g., lighten, darken), string manipulation,
and more.
Inheritance: Sass offers inheritance with the `@extend` directive, allowing one
selector to inherit styles from another.
Modularization: Both Sass and LESS allow you to break your CSS into smaller,
modular files that can be imported into one main file. This keeps your stylesheets
organized and maintainable.
Setting Up Sass
Install Node.js and npm (if you haven't already).
Install Sass globally using npm: npm install -g sass
Compile Sass files using the following command: sass input.scss output.css
Compile LESS files using the following command: lessc input.less output.css
Understanding Keyframes
Keyframes allow you to define intermediate steps in your animation,
specifying how styles should change at various points. You can use
keyframes to create complex animations by describing the state of an
element at different times during its lifecycle.
Easing Functions
Easing functions control the speed of the animation, making it appear more
natural. By default, animations follow a linear path, but easing functions allow
for smooth acceleration and deceleration. Here are some common easing
functions:
ease: Starts slow, becomes fast, and then slows down again.
linear: The animation moves at a constant speed.
ease-in: Starts slowly and accelerates.
ease-out: Starts fast and decelerates.
ease-in-out: Starts and ends slowly, with acceleration in the middle.
cubic-bezier: Custom easing, where you define your own acceleration curve
using four control points.
Example: Animation with Easing Functions
.move-box {
width: 100px;
height: 100px;
background-color: #e74c3c;
animation: move-left-right 2s cubic-bezier(0.42, 0, 0.58, 1) infinite;
}
.scale-rotate-box {
width: 100px;
height: 100px;
background-color: #f39c12;
animation: scale-rotate 3s ease-in-out infinite;
}
Staggering Animations
Staggering animations can make elements animate one after another,
creating a more dynamic and fluid visual effect. You can achieve this by
applying a delay to each animation, creating a cascading effect.
.staggered-items div {
width: 50px;
height: 50px;
background-color: #9b59b6;
margin: 10px;
opacity: 0;
animation: fadeIn 1s forwards;
}
.staggered-items div:nth-child(1) {
animation-delay: 0s;
}
.staggered-items div:nth-child(2) {
animation-delay: 0.3s;
}
.staggered-items div:nth-child(3) {
animation-delay: 0.6s;
}
Chapter 19: CSS Transforms and 3D
Transforms
CSS transforms are a powerful way to manipulate the position, size, and
orientation of elements. With transforms, you can scale, rotate, skew, and
move elements in both 2D and 3D spaces. This chapter will explore the
basics of 2D transforms, followed by an introduction to 3D transforms,
allowing you to create interactive and visually dynamic designs.
Basic 2D Transforms
In 2D transforms, we can move, scale, rotate, and skew elements on the X
and Y axes. These transforms allow for simple yet effective animations and
interactions on the web.
Scaling Elements
The scale() transform allows you to increase or decrease the size of an
element. It works on both the X and Y axes, which means you can scale an
element proportionally or non-proportionally.
Rotating Elements
The rotate() transform rotates an element around a specified point, often
the center of the element. You can specify the angle of rotation in degrees.
Skewing Elements
The skew() transform allows you to slant an element along the X or Y axis.
This can create interesting effects when combined with other transforms.
3D Transforms
3D transforms add depth and perspective to your elements, enabling you to
create more immersive and dynamic effects. By using the perspective
property and 3D transform functions, you can manipulate elements in three
dimensions.
.element {
width: 100px;
height: 100px;
background-color: #9b59b6;
transform: rotateY(45deg); /* 3D Rotation around the Y-axis */
}
3D Cube Example
One of the most exciting uses of 3D transforms is creating 3D objects, like
cubes. By combining multiple 3D transforms, you can create rotating cubes,
carousels, and other interactive 3D effects.
.cube {
position: relative;
width: 100%;
height: 100%;
transform-style: preserve-3d; /* Preserve 3D space */
animation: rotateCube 3s infinite linear;
}
.cube div {
position: absolute;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.1);
border: 2px solid #3498db;
}
.cube .front {
transform: translateZ(50px);
}
.cube .back {
transform: rotateY(180deg) translateZ(50px);
}
.cube .left {
transform: rotateY(-90deg) translateZ(50px);
}
.cube .right {
transform: rotateY(90deg) translateZ(50px);
}
.cube .top {
transform: rotateX(90deg) translateZ(50px);
}
.cube .bottom {
transform: rotateX(-90deg) translateZ(50px);
}
@keyframes rotateCube {
0% {
transform: rotateY(0deg);
}
100% {
transform: rotateY(360deg);
}
}
Chapter 20: CSS Filters and Effects
CSS filters are a powerful tool that allows you to apply various visual effects
to elements, such as blurring, brightness adjustment, contrast, grayscale,
and more. Filters can be used to create engaging effects for images,
backgrounds, and even text. In this chapter, we will explore the most
common CSS filters and how to use them creatively to enhance your web
designs.
Applying Filters
CSS filters are applied using the filter property, which can take a list of
filter functions. Each filter function applies a specific effect, such as blur or
brightness, to the selected element.
/* Increasing brightness */
.element {
width: 200px;
height: 200px;
background-color: #f39c12;
filter: brightness(150%); /* Increase brightness */
}
Example: Adjusting Contrast
/* Increasing contrast */
.element {
width: 200px;
height: 200px;
background-color: #2ecc71;
filter: contrast(200%); /* Increase contrast */
}
Example: Grayscale
/* Converting to grayscale */
.element {
width: 200px;
height: 200px;
background-color: #e74c3c;
filter: grayscale(100%); /* Convert to grayscale */
}
Example: Sepia
Example: Invert
/* Inverting colors */
.element {
width: 200px;
height: 200px;
background-color: #3498db;
filter: invert(100%); /* Invert colors */
}
Combining Filters
Filters can be combined to create complex visual effects. You can apply
multiple filters to an element by separating them with spaces. Here's how
you can combine different filters to achieve more interesting results.
Minifying CSS
Minification is the process of removing unnecessary characters from your
CSS files, such as whitespace, comments, and line breaks. This reduces the
file size and helps speed up loading times, especially for mobile users with
limited bandwidth.
Critical CSS
Critical CSS is the minimum amount of CSS required to render the above-
the-fold content of a page. By extracting and inlining this CSS, you can
speed up the page's first render and reduce render-blocking.
Debugging CSS
Debugging CSS can be tricky, especially when dealing with layout issues,
unexpected behavior, or style conflicts. The key is to isolate the problem,
inspect the styles, and identify the root cause.
Browser Compatibility
Ensuring cross-browser compatibility is one of the most important aspects
of CSS development. Different browsers interpret CSS properties in slightly
different ways, so it's essential to test your styles on multiple browsers and
devices.
Using the "outline" property to highlight and visualize elements and their
boundaries.
Temporarily setting background colors or borders to better understand
the positioning of elements.
Checking for floating elements that may cause layout shifts.
Inspecting CSS properties like position, z-index, flex, and grid to
ensure proper layout behavior.
1. Attribute Selectors
Attribute selectors allow you to target elements based on their attributes or
values. For example, you can style all links that point to an external URL or all
elements with a specific data attribute.
2. Combinator Selectors
Combinators allow you to define relationships between elements. For
example, selecting a div inside a nav or a sibling h2 inside a section.
/* Block */
.button {
background-color: blue;
}
/* Element */
.button__icon {
margin-right: 8px;
}
/* Modifier */
.button--large {
font-size: 18px;
}
2. CSS Methodologies
Several CSS methodologies can help in writing scalable CSS:
/* Inefficient selector */
div > p > span > a {
color: blue;
}
Write descriptive class names that clearly define the purpose of the
element.
Group related CSS rules together and use consistent formatting.
Comment your CSS to explain complex styles or decisions.
Use a CSS linter to enforce coding standards and catch errors early.
Keep your CSS modular and avoid making styles too specific or tightly
coupled with HTML structure.
Mobile-first Design
Mobile-first design is an approach where you prioritize designing for mobile
screens first, then progressively enhance the layout and functionality for
larger screens. This ensures that your website performs well on small
devices, where space and resources are limited.
/* Mobile-first styles */
body {
font-size: 16px;
padding: 10px;
}
nav {
display: block;
}
nav {
display: flex;
justify-content: space-between;
}
}
nav {
justify-content: space-evenly;
}
}
header {
height: 10vh;
background-color: lightblue;
}
Accessibility in CSS
Accessibility (a11y) is the practice of making web content usable by all users,
including people with disabilities. This section will cover how to implement
accessibility principles in your CSS design to ensure that your website can
be used by a diverse range of people.
1. Color Contrast
One of the key elements in accessibility is ensuring sufficient color contrast.
Text should be readable for people with low vision or color blindness. Tools
like the W3C Contrast Checker can help determine whether your text has
enough contrast against its background.
.element {
animation: example 3s infinite linear;
animation-timing-function: ease-in-out;
}