CSS Handbook
CSS Handbook
Learn with us :
Telegram: https://t.me/EmmersiveLearning
Youtube: https://www.youtube.com/@EmmersiveLearning/
1. CSS Roadmap
Here's a complete roadmap to mastering CSS, broken down into levels, so you
can go from beginner to advanced while covering all the essential concepts.
1. Basics of CSS
These are the foundational concepts of CSS that you need to understand before
moving on to more advanced topics.
1
1.4 CSS Units
2.3 Sizing
3. Layout Techniques
3.1 Positioning
2
3.2 Flexbox
4. Styling Essentials
4.1 Typography
● Setting text and background colors using hex, RGB, HSL, and named
colors.
● Background images (background-image, background-position,
background-size, background-repeat).
3
4.3 Borders and Shadows
5. Responsive Design
● Use of relative units like %, em, rem, vw, vh for fluid layouts.
6. Advanced CSS
4
● Animations: Keyframes (@keyframes), animation properties for more
complex animations.
CSS code
:root {
--primary-color: #3498db;
}
h1 {
color: var(--primary-color);
}
5
7.1 CSS Frameworks
7.2 Preprocessors
● Sass, Less: CSS preprocessors that allow you to use features like
variables, nesting, and mixins to write more maintainable CSS.
● Minifying CSS.
● Removing unused CSS (tree-shaking).
8.3 CSS-in-JS
6
9.1 Reducing Repaints and Reflows
7
Bonus: Projects for Practice
By following this roadmap, you'll progressively learn the essential skills needed to
master CSS from the ground up! Let me know if you want to focus on a particular
topic in more depth.
2. Basics of CSS
1. What is CSS?
CSS (Cascading Style Sheets) is used to style and design the layout of web
pages. It allows you to change the appearance of HTML elements, such as color,
size, spacing, and positioning.
8
● CSS is the language we use to style an HTML document.
● CSS describes how HTML elements should be displayed.
9
1. Introduction to CSS
CSS stands for Cascading Style Sheets. It describes how HTML elements are to be displayed
on screen, paper, or in other media. CSS saves a lot of work as it can control the layout of
multiple web pages all at once.
2. CSS Syntax
10
CSS is written with selectors and rules. Here's the basic syntax:
selector {
property: value;
}
Example:
h1 {
color: blue;
font-size: 24px;
}
This CSS code makes all <h1> elements blue and increases the font size to 24
pixels.
11
3. Applying CSS
You can apply styles directly to individual HTML elements using the style
attribute:
Example :
12
You can write CSS within a <style> tag inside the <head> section of your
HTML document:
<head>
<style>
h1 {
color: blue;
font-size: 24px;
}
</style>
</head>
This is the most common and recommended way. You write the CSS in a
separate file (e.g., styles.css) and link it to your HTML file using a <link>
tag:
<head>
<link rel="stylesheet" href="styles.css">
</head>
In styles.css:
h1 {
color: blue;
font-size: 24px;
}
4. CSS Selectors
13
Selectors determine which HTML elements to style.
p {
color: red;
}
Targets elements by their class attribute. Classes allow you to apply the same
style to multiple elements.
14
<p class="highlight">This is a paragraph.</p>
<p class="highlight">This is another paragraph.</p>
.highlight {
background-color: yellow;
}
4.3 ID Selector
Targets an element by its unique id. IDs are used for unique elements on the
page.
CSS:
#special {
color: green;
}
* {
margin: 0;
padding: 0;
}
15
Targets elements that are descendants of a specific element.
HTML :
<div class="container">
<p>This is a paragraph inside a div.</p>
</div>
CSS:
.container p {
font-size: 18px;
}
16
1. Content: The actual content (e.g., text or image).
2. Padding: Space between the content and the border.
3. Border: The edge around the padding.
4. Margin: Space outside the border between other elements.
Example:
div {
width: 200px;
padding: 10px;
border: 5px solid black;
margin: 20px;
}
This will create a div box with content, padding, a border, and a margin around
it.
6. CSS Units
CSS allows you to define sizes, widths, and lengths in various units. These units
can be relative or absolute.
● em: Relative to the font size of the element (e.g., 1em is equal to the
current font size).
● rem: Relative to the font size of the root element (html).
● %: Relative to the parent element's size.
17
● px (pixels): A fixed size in pixels.
● cm, mm: Centimeters, millimeters (rarely used in web design).
p {
font-family: Arial, sans-serif;
font-size: 16px;
font-weight: bold;
}
h1 {
text-align: center;
}
18
8.1 Color
You can set colors using keywords, hex codes, RGB, or HSL.
8.2 Backgrounds
div {
background-color: #f0f0f0;
background-image: url('background.jpg');
background-size: cover;
}
9.1 Margins
p {
margin: 20px; /* Adds a 20px margin to all sides */
}
19
p {
margin-top: 10px;
margin-right: 15px;
margin-bottom: 10px;
margin-left: 5px;
}
9.2 Padding
Padding clears space inside the element, between the content and the border.
div {
padding: 10px;
}
div {
padding-top: 10px;
padding-right: 15px;
padding-bottom: 10px;
padding-left: 5px;
}
10. Border
div {
border: 2px solid black;
20
border-radius: 10px; /* Makes the corners round */
}
p {
margin: 10px 20px 10px 20px; /* top, right, bottom, left */
}
● Font Shorthand:
p {
font: bold 16px Arial, sans-serif;
}
21
Components of the Box Model:
Each element on a webpage is essentially a box, and the box model consists of
four parts:
You can control each part of the box model with specific CSS properties.
1.1 Content
The content is the actual text or image inside the element. Its size is controlled by
properties like width and height.
22
div {
width: 200px;
height: 150px;
}
1.2 Padding
Padding is the space between the content and the border. You can set padding
for each side (top, right, bottom, left) individually or set it all at once.
div {
padding: 20px; /* Applies padding of 20px to all sides */
}
div {
padding-top: 10px;
padding-right: 15px;
padding-bottom: 10px;
padding-left: 5px;
}
1.3 Border
Borders surround the padding. You can control the width, style, and color of the
border.
div {
border: 2px solid black;
}
23
● Width: How thick the border is (e.g., 2px).
● Style: Defines how the border looks (e.g., solid, dashed, dotted, etc.).
● Color: Sets the color of the border.
You can also use border-radius to make the border's corners round:
div {
border-radius: 10px; /* Creates rounded corners */
}
1.4 Margin
Margins create space between the element’s border and other elements on the
page.
div {
margin: 20px; /* Adds 20px margin on all sides */
}
div {
margin: 20px; /* Adds 20px margin on all sides */
}
div {
margin-top: 10px;
margin-right: 15px;
24
margin-bottom: 10px;
margin-left: 5px;
}
Example:
div {
width: 200px;
padding: 20px;
border: 5px solid black;
margin: 10px;
}
● Total width = 200px + 20px (left padding) + 20px (right padding) + 5px (left
border) + 5px (right border) + 10px (left margin) + 10px (right margin) =
270px
● Total height = Similarly calculated with height, padding, border, and
margin values.
25
4. CSS Display
The display property controls how an element is displayed on the page, affecting
how it interacts with other elements.
Elements like <div>, <p>, and <h1> are block-level elements. Block-level
elements:
div {
display: block;
}
Example:
26
<div>This is a block element</div>
<div>This will appear on a new line</div>
Elements like <span>, <a>, and <strong> are inline elements. Inline elements:
span {
display: inline;
}
Example:
When you set an element’s display to none, it is completely removed from the
layout and is invisible.
div {
display: none;
}
Example:
27
<div>This text will not be displayed</div>
● The element remains on the same line (like inline), but you can set
width and height (like block).
span {
display: inline-block;
width: 100px;
height: 50px;
background-color: yellow;
}
Example:
When you set display: flex, the container becomes a flexbox container,
allowing you to arrange its children in rows or columns with flexible layouts. This
is very powerful for layouts and responsive design.
.container {
display: flex;
justify-content: space-between;
}
28
Example:
<div class="container">
<div>Box 1</div>
<div>Box 2</div>
<div>Box 3</div>
</div>
display: grid makes an element a grid container, allowing you to place items
in rows and columns.
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr; /* Three equal
columns */
}
Example:
html
Copy code
<div class="container">
<div>Item 1</div>
<div>Item 2</div>
29
<div>Item 3</div>
</div>
Conclusion
● The box model gives structure to how elements are sized and spaced with
content, padding, borders, and margins.
● The display property determines how elements are laid out on the page
(block, inline, none, flex, grid, etc.).
These concepts are the foundation of CSS layout design. Let me know if you'd
like to dive deeper into any particular topic!
5. Layout Techniques
To understand layout techniques in CSS, you need to be familiar with several key
methods used to structure web pages. Layout techniques help in organizing
elements on a page, making it responsive and user-friendly.
30
CSS layouts are crucial for arranging elements on a web page in a structured
and visually appealing way. Let's break down the most important concepts and
techniques used in CSS for creating layouts:
31
1. CSS Display Property
2. CSS Positioning
3. Flexbox
4. Grid Layout
5. Float
6. Responsive Design
The display property in CSS is crucial for controlling how elements are
rendered in the document. It determines the display behaviour of an element,
including how it interacts with other elements around it. Here's an in-depth guide
to the display property:
32
33
Basic Display Values
display: block;
● Block-level elements take up the full width available, and each element
starts on a new line.
Css code
.block-element {
display: block;
width: 100%;
background-color: lightblue;
}
html code
34
display: inline;
● Inline elements do not start on a new line and only take up as much width
as necessary.
.inline-element {
display: inline;
color: red;
}
Html code
35
<p>This is an <span class="inline-element">inline</span>
element.</p>
display: inline-block;
● Inline-block elements are like inline elements but allow for width and
height to be set.
.inline-block-element {
display: inline-block;
width: 150px;
height: 100px;
background-color: lightgreen;
}
HTML code
<div class="inline-block-element">Inline-block</div>
<div class="inline-block-element">Element</div>
2. CSS Positioning
36
Here's a comprehensive guide:
1. position: static;
Css code
37
.static-box {
position: static;
background-color: lightgrey;
}
Html code
2. position: relative;
Css code
.relative-box {
position: relative;
top: 20px; /* Moves the element 20px down from its original
position */
left: 30px; /* Moves the element 30px to the right from its
original position */
background-color: lightblue;
}
Html code
38
<div class="relative-box">This is a relatively positioned
element.</div>
3. position: absolute;
Css code
.absolute-container {
position: relative;
width: 300px;
height: 200px;
background-color: lightgrey;
}
.absolute-box {
position: absolute;
top: 50px;
right: 20px;
39
background-color: lightcoral;
padding: 10px;
}
Html code
<div class="absolute-container">
<div class="absolute-box">This is an absolutely positioned
element.</div>
</div>
4. position: fixed;
Css code
.fixed-box {
position: fixed;
bottom: 10px;
right: 10px;
background-color: lightgreen;
padding: 20px;
40
}
Html code
5. position: sticky;
Css code
.sticky-box {
position: sticky;
top: 0; /* The element will stick to the top of the viewport
*/
background-color: yellow;
padding: 10px;
}
Html code
41
<div class="sticky-box">This is a sticky positioned
element.</div>
<p>Scroll down to see how the element behaves.</p>
<p style="height: 1000px;"></p> <!-- Just to create space for
scrolling -->
6. Understanding Z-Index
z-index: This property controls the stacking order of elements that overlap.
Elements with a higher z-index appear on top of those with a lower z-index.
It only works on positioned elements (relative, absolute, fixed, or
sticky).
Css code
.box1 {
position: absolute;
top: 50px;
left: 50px;
width: 100px;
height: 100px;
background-color: lightcoral;
z-index: 10; /* This element will be on top */
}
.box2 {
position: absolute;
42
top: 80px;
left: 80px;
width: 100px;
height: 100px;
background-color: lightblue;
z-index: 5; /* This element will be below box1 */
}
Html code
Understanding the position property in CSS allows you to create dynamic and
responsive layouts by controlling exactly where elements appear on the page.
43
3. Flexbox
Flexbox (Flexible Box Layout) is a CSS layout module designed to help distribute
space within a container and align items efficiently. It’s ideal for designing
complex layouts and responsive web designs. Flexbox simplifies creating flexible
and adaptable structures for websites.
44
Here’s a detailed guide to understanding Flexbox:
Before diving into the properties, it's important to understand the basic terms:
● Flex Container: The parent element that holds the flex items. It’s set by
using display: flex;.
● Flex Items: The direct children of the flex container.
.flex-container {
display: flex;
background-color: lightgrey;
padding: 10px;
}
45
<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>
1. flex-direction
● Defines the main axis along which the flex items are placed in the flex
container.
46
● Values:
○ row (default): Left to right in a row.
○ row-reverse: Right to left in a row.
○ column: Top to bottom in a column.
○ column-reverse: Bottom to top in a column.
.flex-container {
display: flex;
flex-direction: row; /* or column, row-reverse,
column-reverse */
}
47
2. justify-content
● Values:
○ flex-start (default): Items are packed toward the start of the axis.
○ flex-end: Items are packed toward the end of the axis.
○ center: Items are centered along the axis.
○ space-between: Items are evenly distributed with the first item at
the start and the last item at the end.
○ space-around: Items are evenly distributed with space before the
first item and after the last item.
○ space-evenly: Items are evenly distributed with equal space
between them.
48
.flex-container {
justify-content: center; /* or flex-start, flex-end,
space-between, space-around, space-evenly */
}
3. align-items
Aligns the flex items along the cross axis (perpendicular to the main axis).
49
● Values:
○ stretch (default): Items are stretched to fill the container.
50
○ flex-start: Items are aligned at the start of the cross axis.
○ flex-end: Items are aligned at the end of the cross axis.
○ center: Items are centred along the cross axis.
○ baseline: Items are aligned along their baselines.
.flex-container {
align-items: center; /* or flex-start, flex-end, stretch,
baseline */
}
4. flex-wrap
Controls whether the flex items should wrap onto multiple lines.
51
● Values:
○ nowrap (default): All items are placed on a single line.
○ wrap: Items wrap onto multiple lines from top to bottom.
○ wrap-reverse: Items wrap onto multiple lines from bottom to top.
.flex-container {
flex-wrap: wrap; /* or nowrap, wrap-reverse */
}
5. Align-content
Aligns rows of flex items when there is extra space in the cross axis.
52
● Values:
○ stretch (default): Rows are stretched to take up the remaining
space.
○ flex-start: Rows are packed toward the start of the cross axis.
○ flex-end: Rows are packed toward the end of the cross axis.
○ center: Rows are centered in the cross axis.
○ space-between: Rows are evenly distributed with the first row at
the start and the last row at the end.
○ space-around: Rows are evenly distributed with space before the
first row and after the last row.
○ space-evenly: Rows are evenly distributed with equal space
between them.
.flex-container {
align-content: space-between; /* or stretch, flex-start,
flex-end, center, space-around, space-evenly */
}
53
1. Order
Specifies the order of the flex items within the container. The default value is 0,
and items with a lower order value appear first.
.
flex-item {
order: 2; /* Default is 0 */
}
54
2. flex-grow
Specifies how much a flex item should grow relative to the other items. The
default value is 0 (no growth).
.flex-item {
flex-grow: 2; /* Item will grow twice as much as items with
flex-grow: 1 */
}
3. flex-shrink
Specifies how much a flex item should shrink relative to the other items. The
default value is 1.
55
.flex-item {
flex-shrink: 1; /* Default value */
}
4. flex-basis
Specifies the initial size of the flex item before any space distribution happens. It
can be set in pixels, percentages, etc.
flex-item {
flex-basis: 100px; /* Default is auto */
}
5. align-self
56
● Allows the default alignment (or the one specified by align-items) to be
overridden for individual flex items.
● Values:
○ auto (default): Inherits from align-items.
○ flex-start: Aligns the item at the start of the cross axis.
○ flex-end: Aligns the item at the end of the cross axis.
○ center: Centers the item along the cross axis.
○ baseline: Aligns the item along its baseline.
○ stretch: Stretches the item to fill the container.
.flex-item {
align-self: flex-end; /* or flex-start, center, baseline,
stretch */
}
5. Examples
flex-container {
display: flex;
justify-content: space-between;
align-items: center;
background-color: lightgrey;
padding: 10px;
}
57
.flex-item {
background-color: lightblue;
padding: 20px;
margin: 5px;
flex-grow: 1;
}
<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>
.flex-container {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 10px;
background-color: lightgrey;
padding: 10px;
}
.flex-item {
background-color: lightcoral;
58
padding: 20px;
width: 30%;
box-sizing: border-box;
}
<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 class="flex-item">Item 4</div>
<div class="flex-item">Item 5</div>
<div class="flex-item">Item 6</div>
</div>
Summary of Flexbox
4. Grid Layout
Grid Layout is a two-dimensional layout system for web pages, allowing you to
arrange elements in rows and columns.
59
Container: The parent element that holds grid items.
css
Copy code
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 10px;
}
●
○ grid-template-columns: Defines the columns of the grid (e.g.,
1fr, 200px).
○ grid-template-rows: Defines the rows of the grid.
○ grid-gap: Adds space between grid items.
●
○ grid-column: Specifies which column the item should occupy.
○ grid-row: Specifies which row the item should occupy.
5. Float
60
Float is an older method used to create layouts by wrapping text around
elements or creating columns.
Left or Right Float: Moves the element to the left or right of its container,
allowing text to wrap around it.
css
Copy code
.box {
float: left;
width: 50%;
}
●
○ clear: Clears the float to prevent overlap.
css
Copy code
.clearfix {
clear: both;
}
6. Responsive Design
Responsive design ensures that your layout adapts to different screen sizes.
Media Queries: Apply different styles based on the device's width, height,
orientation, etc.
css
61
Copy code
@media (max-width: 600px) {
.container {
flex-direction: column;
}
}
Responsive Units: Use relative units like %, em, rem, vw, and vh instead of
fixed units like px.
css
Copy code
.responsive {
width: 100%;
padding: 2em;
}
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
62
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Flexbox Layout</title>
<style>
.container {
display: flex;
justify-content: space-between;
align-items: center;
height: 100vh;
}
.item {
background-color: lightblue;
padding: 20px;
flex: 1;
margin: 10px;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
63
<div class="item">Item 3</div>
</div>
</body>
</html>
This will create a horizontal layout with three equal-width boxes, evenly spaced
within the container.
6. Styling Essentials
When it comes to styling essentials in CSS, there are several core concepts
that you should master. These styling basics are the foundation of how elements
are displayed, colored, and adjusted on a webpage.
1. Selectors
Selectors are used to target HTML elements that you want to style.
Common Selectors:
Element Selector: Targets all elements of a specific type.
p {
color: blue;
}
64
Class Selector: Targets elements with a specific class name.
.box {
background-color: lightblue;
}
#header {
font-size: 24px;
}
* {
margin: 0;
padding: 0;
}
input[type="text"] {
border: 1px solid black;
}
2. Colors
65
Color is one of the most basic styling properties. You can specify colors in CSS
using:
Named Colors:
body {
background-color: lightgray;
}
Hex Codes:
h1 {
color: #ff5733;
}
RGB Values:
p {
color: rgb(255, 87, 51);
}
div {
background-color: rgba(0, 0, 0, 0.5); /* Black with 50%
transparency */
}
66
HSL and HSLA (Hue, Saturation, Lightness, Alpha):
div {
background-color: rgba(0, 0, 0, 0.5); /* Black with 50%
transparency */
}
span {
color: hsl(120, 100%, 50%); /* Pure green */
}
3. Typography
body {
font-family: 'Arial', sans-serif;
}
h1 {
font-size: 32px;
}
67
Font-Weight: Specifies the thickness of the font.
p {
font-weight: bold;
}
p {
line-height: 1.5;
}
p {
line-height: 1.5;
}
h2 {
text-align: center;
}
a {
text-decoration: none;
}
h1 {
68
text-transform: uppercase;
}
4. Backgrounds
body {
background-color: lightyellow;
}
div {
background-image: url('background.jpg');
}
div {
background-repeat: no-repeat;
}
69
div {
background-repeat: no-repeat;
}
div {
background-position: center;
}
Controlling the space between and around elements is crucial for layout.
Padding:
Padding is the space inside the element, between the content and the border.
div {
padding: 20px; /* Adds space inside the div */
}
Margin:
70
Margin is the space outside the element, between the border and the
neighboring elements.
div {
margin: 15px; /* Adds space outside the div */
}
div {
padding: 10px 20px 15px 5px; /* Top, Right, Bottom, Left */
margin-top: 20px;
margin-left: 10px;
}
6. Borders
Borders outline elements and can be customized in terms of style, color, and
width.
Border Properties:
border: Set the width, style, and color in one line.
div {
border: 2px solid black;
}
71
div {
border-radius: 10px;
}
div {
width: 100px;
}
div {
height: 200px;
}
● px: Pixels
● %: Percentage of the parent element's size
● em/rem: Relative to the font size
8. Display Property
72
The display property controls how an element is displayed in the document.
div {
display: block;
}
inline: Only takes up as much width as its content and remains on the same line
as other elements.
span {
display: inline;
}
inline-block: Behaves like inline, but allows width and height to be set.
img {
display: inline-block;
}
none: The element is not displayed at all (removed from the layout).
div {
display: none;
}
73
9. Visibility
The visibility property controls whether an element is visible or hidden, but it still
takes up space in the layout.
p {
visibility: visible;
}
p {
visibility: hidden;
}
Syntax:
div {
box-shadow: 10px 10px 5px rgba(0, 0, 0, 0.5); /* Offset-X,
Offset-Y, Blur-Radius, Color */
}
11. Opacity
74
The opacity property controls the transparency of an element.
div {
opacity: 0.7;
}
12. Cursor
The cursor property changes the mouse pointer when hovering over an element.
a {
cursor: pointer;
}
div {
cursor: default;
}
75
Transitions and animations enhance user experience by animating property
changes.
Transition:
Allows smooth changes between property values.
div {
transition: background-color 0.3s ease-in-out;
}
div:hover {
background-color: yellow;
}
Animation:
More complex animations are defined with keyframes.
@keyframes move {
0% { transform: translateX(0); }
100% { transform: translateX(100px); }
}
div {
animation: move 2s infinite;
}
76
3. Typography: Control fonts, size, weight, and alignment.
4. Backgrounds: Set background images and colors.
5. Spacing: Adjust margins and padding.
6. Borders: Style element borders and add rounded corners.
7. Sizing: Set width and height of elements.
8. Display: Control how elements are rendered.
9. Visibility: Hide or show elements.
10. Box Shadow: Add shadows to elements.
11.Opacity: Set transparency.
12. Cursor: Change the mouse pointer.
13. Transition and Animation: Add smooth animations.
7. Responsive Design
Responsive design in CSS is all about ensuring that your website or web
application looks good and functions well on all devices, from small mobile
phones to large desktop screens. It’s a key aspect of modern web development
and is achieved by using techniques that adjust the layout, typography, images,
and other elements based on the screen size.
77
Key Concepts in Responsive Design
1. Fluid Layouts
Instead of using fixed pixel values for widths, use relative units like percentages,
em, or rem to make layouts more adaptable to various screen sizes.
78
.container {
width: 600px; /* Fixed width, doesn't adapt to different
screens */
}
.container {
width: 80%; /* Width changes according to screen size */
}
Relative Units:
2. Media Queries
Media queries allow you to apply different styles depending on the screen size
or device. They are one of the most powerful tools for creating responsive
designs.
Basic Syntax:
79
.container {
width: 100%;
}
}
Common Breakpoints:
80
3. Flexible Images
Images should be responsive, so they scale with the size of the screen rather
than having a fixed width.
img {
max-width: 100%;
height: auto;
}
This ensures that the image never exceeds the width of its container and scales
proportionally.
You can also use media queries to serve different image sizes based on the
device's screen resolution or width.
4. Responsive Typography
Instead of using fixed pixel sizes for fonts, use em or rem to allow font sizes to
scale based on the user’s settings or screen size.
Example:
body {
81
font-size: 16px; /* Default for larger screens */
}
Viewport-Relative Units:
You can use vw (viewport width) and vh (viewport height) to scale fonts relative
to the screen size.
h1 {
font-size: 5vw; /* Heading size will change based on the
viewport width */
}
CSS Flexbox is a layout model that makes it easy to create flexible, responsive
layouts. Flexbox adjusts the size of elements automatically, and can reorder them
for different screen sizes.
.container {
display: flex;
flex-wrap: wrap;
82
justify-content: space-between;
}
.item {
flex: 1 1 30%; /* Flex items take up 30% of the container's
width */
margin: 10px;
}
CSS Grid is another powerful layout system that allows you to create complex
layouts using rows and columns. Like Flexbox, CSS Grid can be made
responsive using media queries.
.container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* 3 equal-width
columns */
gap: 20px;
}
83
.container {
grid-template-columns: 1fr; /* Single column on mobile
*/
}
}
7. Mobile-First Approach
A mobile-first approach means starting your CSS with styles optimized for
small screens and then using media queries to adjust the layout for larger
screens. This ensures a good experience on mobile devices by default.
Example:
/* Mobile styles */
.container {
width: 100%;
}
/* Desktop styles */
@media only screen and (min-width: 1024px) {
.container {
width: 60%;
}
}
84
8. Frameworks and Libraries
You can also use CSS frameworks like Bootstrap or Tailwind CSS, which come
with built-in responsive utilities and components.
<div class="container">
<div class="row">
<div class="col-md-6 col-lg-4">Column 1</div>
<div class="col-md-6 col-lg-4">Column 2</div>
<div class="col-md-6 col-lg-4">Column 3</div>
</div>
</div>
1. Fluid Layouts: Use percentages or relative units like em and rem for
layout sizes.
2. Media Queries: Apply different styles for different screen sizes.
85
3. Flexible Images: Ensure images are responsive using max-width:
100%.
4. Responsive Typography: Use relative units or viewport-based units for
fonts.
5. CSS Flexbox & Grid: Create responsive layouts that adjust based on
screen size.
6. Mobile-First Approach: Start with mobile styles and use media queries for
larger screens.
8. Advanced CSS
Advanced CSS techniques help you take your web design skills to the next level,
allowing you to create more complex, dynamic, and visually appealing layouts
and effects. Here’s a breakdown of the key topics and concepts that fall under
advanced CSS:
CSS preprocessors are scripting languages that extend CSS and make it more
maintainable and scalable by adding features like variables, nesting, mixins, and
more.
Variables: Store values like colors or font sizes that you can reuse throughout
your CSS.
SCSS code:
$primary-color: #3498db;
86
body {
background-color: $primary-color;
}
nav {
ul {
list-style: none;
li {
display: inline-block;
}
}
}
@mixin button-style($color) {
background-color: $color;
padding: 10px;
border-radius: 5px;
}
.btn-primary {
@include button-style(#3498db);
}
87
CSS custom properties (variables) allow you to define reusable values in your
CSS without using a preprocessor.
Define a Variable:
:root {
--primary-color: #3498db;
}
body {
color: var(--primary-color);
}
CSS Grid is a powerful layout system that provides greater control over 2D
layouts, both horizontally and vertically. Beyond basic grid setups, advanced
techniques include creating more complex layouts with named grid areas, grid
line numbering, and alignment properties.
88
.container {
display: grid;
grid-template-areas:
"header header header"
"sidebar content content"
"footer footer footer";
grid-template-columns: 1fr 2fr;
grid-template-rows: auto 1fr auto;
}
Aligning Items:
.container {
align-items: center; /* Align items vertically */
justify-items: center; /* Align items horizontally */
}
.item {
grid-column: 1 / 3; /* Span from column line 1 to 3 */
grid-row: 1 / 2; /* Span from row line 1 to 2 */
}
89
Flexbox is a 1D layout model used for arranging items within a container,
especially for dynamic layouts. Some advanced techniques include:
Aligning Items:
.container {
display: flex;
align-items: stretch; /* Align flex items to fill the
container */
justify-content: space-around; /* Distribute items evenly */
}
Responsive Flexbox:
CSS animations and transitions allow you to add dynamic, interactive elements
to your design.
Example :
90
.box {
width: 100px;
height: 100px;
background-color: blue;
transition: background-color 0.3s ease, transform 0.5s;
}
.box:hover {
background-color: red;
transform: scale(1.1); /* Scale slightly on hover */
}
@keyframes bounce {
0% { transform: translateY(0); }
50% { transform: translateY(-50px); }
100% { transform: translateY(0); }
}
.box {
animation: bounce 2s infinite; /* Animate continuously */
}
●
● Animation Timing: You can control animation speed using functions like
ease-in, ease-out, linear, and more.
91
CSS transform allows you to scale, rotate, translate, or skew elements, both in
2D and 3D space.
2D Transforms:
Example :
.box {
transform: scale(1.2) rotate(45deg); /* Scale and rotate the
element */
}
3D Transforms:
.box {
transform: perspective(500px) rotateX(45deg) rotateY(45deg);
/* Apply 3D perspective */
}
.element {
clip-path: circle(50% at 50% 50%); /* Creates a circular
clip */
}
92
Polygon Shape:
.element {
clip-path: polygon(50% 0%, 0% 100%, 100% 100%); /* Creates a
triangle */
}
● Pseudo-Classes:
○ :hover: Styles an element when hovered.
○ :nth-child(): Styles based on the element's position in a list.
Example :
li:nth-child(odd) {
background-color: #f2f2f2; /* Alternate row coloring */
}
● Pseudo-Elements:
○ ::before: Insert content before an element.
○ ::after: Insert content after an element.
.box::after {
93
content: 'Learn CSS!';
display: block;
color: red;
}
Responsive design doesn’t just involve media queries but also thinking about
how your layout and components adapt in terms of flexibility and scalability.
Responsive Images with srcset: Use srcset to serve different image sizes
based on the device's resolution or screen size.
<img src="small.jpg"
srcset="medium.jpg 768w, large.jpg 1200w"
alt="Responsive image">
94
10. Advanced Selectors
a[href^="https"] {
color: green; /* Style links that start with https */
}
h1 ~ p {
color: blue; /* Style all p elements that are siblings of h1
*/
}
p:not(.highlight) {
color: gray; /* Style all p elements except those with the
class "highlight" */
}
CSS Variables: CSS variables can be defined globally or locally and used
dynamically.
:root {
--primary-color: #3498db;
}
95
Calc() Function: Use calc() for dynamic calculations within your CSS.
.container {
width: calc(100% - 20px); /* Subtracting a fixed value from
a percentage */
}
Custom Fonts:
@font-face {
font-family: 'MyCustomFont';
src: url('myfont.woff2') format('woff2');
}
body {
font-family: 'MyCustomFont', sans-serif;
}
● Icon Fonts: Use libraries like Font Awesome to easily add scalable icons
to your site.
Conclusion
96
Mastering advanced CSS techniques requires understanding both the theoretical
concepts and their practical applications. Whether you’re working with complex
layouts using Flexbox or Grid, enhancing user experience with animations, or
optimizing for responsiveness, advanced CSS enables you to build modern,
flexible, and visually stunning web designs.
CSS Frameworks
CSS frameworks provide pre-written, reusable code in the form of grid systems,
typography, UI components, and utility classes that make styling web applications
faster and more consistent. Let’s cover the most popular CSS frameworks:
97
Frameworks in Catagories.
98
1. Bootstrap
Bootstrap is one of the most widely used CSS frameworks. It offers a responsive
grid system, ready-to-use UI components, and powerful utilities.
99
<div class="container">
<div class="row">
<div class="col-md-6">Column 1</div>
<div class="col-md-6">Column 2</div>
</div>
</div>
2. Tailwind CSS
Tailwind CSS is a utility-first CSS framework that offers low-level utility classes
for building custom designs directly in your HTML.
Utility Classes: Instead of prebuilt components, Tailwind allows you to use small
utility classes to style elements.
100
Background</div>
3. Foundation
<div class="grid-container">
<div class="grid-x grid-margin-x">
<div class="cell small-6">Column 1</div>
<div class="cell small-6">Column 2</div>
</div>
</div>
4. Bulma
101
Flexbox-Based: Bulma’s grid system and layout are built with Flexbox, offering
flexibility in alignment and positioning.
<div class="columns">
<div class="column is-half">Column 1</div>
<div class="column is-half">Column 2</div>
</div>
Utility Classes: Bulma provides utility classes for common CSS properties such
as spacing, typography, and alignment.
CSS Preprocessors
CSS preprocessors allow you to write CSS more effectively by using features like
variables, nesting, mixins, functions, and imports. Preprocessors compile into
regular CSS, which is then used by the browser.
Sass is the most popular CSS preprocessor. It extends CSS by adding features
that make your styles more maintainable and reusable.
Variables: Variables allow you to store CSS values like colors, fonts, and sizes.
$primary-color: #3498db;
102
body {
background-color: $primary-color;
}
Nesting: Sass allows you to nest CSS selectors, making your code more
readable.
nav {
ul {
list-style: none;
li {
display: inline-block;
}
}
}
Mixins: Mixins are reusable blocks of CSS that can be called anywhere in your
code.
@mixin button-style($color) {
background-color: $color;
padding: 10px;
border-radius: 5px;
}
.btn-primary {
@include button-style(#3498db);
}
Partials and Import: Sass allows you to split your CSS into smaller, modular
files and import them as needed.
103
// _header.scss
header {
background: #fff;
}
// main.scss
@import 'header';
LESS is another CSS preprocessor that is similar to Sass but with slightly
different syntax and features.
@primary-color: #3498db;
body {
background-color: @primary-color;
}
Nesting: LESS also supports nesting, making your CSS more structured.
nav {
ul {
list-style: none;
li {
display: inline-block;
}
}
}
104
Mixins: Like Sass, LESS allows you to define reusable blocks of code using
mixins.
.button-style(@color) {
background-color: @color;
padding: 10px;
border-radius: 5px;
}
.btn-primary {
.button-style(#3498db);
}
3. Stylus
Stylus is a less popular but very powerful CSS preprocessor. It offers unique
syntax options and features similar to Sass and LESS.
Variables: Stylus allows you to define variables without any special characters.
primaryColor = #3498db
body
background-color: primaryColor
nav
ul
list-style none
li
105
display inline-block
nav
ul
list-style none
li
display inline-block
border-radius(n)
-webkit-border-radius n
-moz-border-radius n
border-radius n
.box
border-radius(10px)
● CSS Frameworks are best when you need a fast way to build responsive,
ready-made designs without starting from scratch.
○ Bootstrap: If you need quick, responsive design with lots of prebuilt
components.
○ Tailwind CSS: If you prefer to build custom designs using utility
classes without overriding existing styles.
106
● CSS Preprocessors are ideal when you want to write cleaner, more
efficient CSS code that is modular and scalable.
○ Sass: Offers a wide range of features for large, scalable projects.
○ LESS: Slightly simpler syntax and easier to use in smaller projects.
You can also combine CSS frameworks and preprocessors to leverage the power
of both. For example, using Bootstrap with Sass allows you to customize
Bootstrap’s variables and components more efficiently.
Conclusion
Learning CSS frameworks and preprocessors can greatly speed up your web
development process. Frameworks like Bootstrap and Tailwind give you prebuilt
components and layout systems, while preprocessors like Sass and LESS allow
you to write more efficient and reusable CSS. Together, they provide a powerful
toolset for building modern, responsive websites.
107
10. CSS Architecture and Best Practices
CSS architecture refers to how your CSS is organized, structured, and
maintained throughout the lifecycle of a project. Following a robust CSS
architecture and best practices is key to building scalable, maintainable, and
efficient stylesheets, especially for large or complex projects.
108
● Separation of Concerns is a principle in CSS where styles are organized
based on their purpose or responsibility. This helps in creating reusable,
maintainable, and modular code.
1.2 Modularity
1.3 Reusability
File Structure
css/
base/
_reset.scss
109
_typography.scss
components/
_buttons.scss
_forms.scss
layouts/
_header.scss
_footer.scss
utilities/
_spacing.scss
_colors.scss
main.scss
BEM is a popular CSS naming convention that helps in writing predictable and
maintainable styles. BEM ensures that class names reflect their purpose, and the
relationship between elements is clear.
Example:
<nav class="navbar">
<ul class="navbar__list">
<li class="navbar__item navbar__item--active">Home</li>
<li class="navbar__item">About</li>
</ul>
110
</nav>
Example:
Avoid overly nested selectors, which can lead to specificity issues and make
styles hard to override or maintain.
Bad Example:
nav ul li a span {
color: red;
}
Good Example:
.navbar__link {
color: red;
111
}
Avoid writing repetitive code. Reuse styles and components where possible.
Bad Example:
.header h1 {
font-size: 24px;
}
.footer h1 {
font-size: 24px;
}
Good Example:
h1 {
font-size: 24px;
}
CSS preprocessors like Sass allow you to use variables to store reusable values
such as colors, fonts, and spacing.
Example:
$primary-color: #3498db;
$secondary-color: #2ecc71;
112
.button {
background-color: $primary-color;
color: #fff;
}
.button--secondary {
background-color: $secondary-color;
}
Example:
Avoid using vague class names like .red-text or .big-button. Instead, use
names that describe the component’s role in the layout.
Bad Example:
<div class="red-text">Alert</div>
Good Example:
113
<div class="alert alert--error">Alert</div>
3. CSS Methodologies
As mentioned earlier, BEM is one of the most popular CSS methodologies that
ensures modular, scalable, and predictable CSS code.
BEM Example:
<div class="card">
<div class="card__header">
<h3 class="card__title">Card Title</h3>
</div>
<div class="card__body">Card Body</div>
<div class="card__footer">Card Footer</div>
</div>
SMACSS organizes CSS into five categories: Base, Layout, Module, State, and
Theme.
114
● Theme: Theme-specific changes.
Atomic CSS is a methodology where styles are broken down into individual,
single-purpose classes. Each class represents one property, making the CSS
highly reusable.
Example:
4. CSS Optimization
Critical CSS refers to inlining the most important styles in the HTML <head> to
avoid blocking the rendering of above-the-fold content. Non-critical styles are
loaded asynchronously.
115
4.3 Avoid Inline Styles
Avoid using inline styles unless absolutely necessary, as they increase specificity
and reduce reusability.
Tools like PurgeCSS can analyze your HTML and remove unused CSS, reducing
the size of your final stylesheet.
5. CSS Performance
● Use modern layout techniques like CSS Grid and Flexbox for more
predictable, maintainable layouts.
● Avoid using float-based layouts as they are harder to maintain and not
suited for modern web design.
116
● Use media queries and a mobile-first approach to create responsive
designs.
Mobile-first Example:
.button {
padding: 8px;
}
● Use properties that take advantage of the GPU (e.g., transform and
opacity) instead of those that cause layout thrashing like top, left, and
width.
Conclusion
117
11. Performance Optimization and
Best Practices in CSS.
Optimizing CSS for performance is crucial for improving page load times,
enhancing user experience, and reducing server load. Below are best practices
and techniques to ensure your CSS is efficient, clean, and performant.
1. Minify CSS
What is Minification?
How to Minify:
118
Instead of having multiple CSS files, combine them into one file to reduce the
number of HTTP requests made by the browser. Fewer requests mean faster
page load times.
CSS Inlining
For critical CSS (styles that are necessary for the initial render), inline the CSS
directly into the HTML document's <head>. This ensures the page can be
rendered immediately, without waiting for external stylesheets to load.
Critical CSS refers to the minimum amount of CSS needed to render the
above-the-fold content of a webpage. Loading this CSS first improves the time to
first paint (TTFP), enhancing the user experience.
<style>
/* Critical CSS for above-the-fold content */
</style>
<link rel="stylesheet" href="styles.css" media="print"
onload="this.media='all'">
<noscript><link rel="stylesheet" href="styles.css"></noscript>
119
4. Reduce Unused CSS
Unused CSS refers to styles that are loaded but never applied to any elements
on the page. Removing unused CSS reduces file size and improves page
performance.
● PurgeCSS: This tool scans your HTML and removes any CSS selectors
that are not being used.
● UnusedCSS: A tool to analyze a webpage and generate a report of
unused CSS.
Bash code
120
Load non-critical CSS files asynchronously to prevent render-blocking, allowing
the browser to continue rendering the page while the CSS is still loading.
Example:
Defer loading of non-critical CSS (like print styles) using media queries:
6. CSS Sprites
Sprites are used to combine multiple images into a single file. This reduces the
number of HTTP requests for images, improving load times.
Instead of loading separate images for icons or small elements, combine them
into a single sprite image and use background-position to display each icon
from the sprite.
.icon {
background-image: url('sprite.png');
background-position: -20px -20px;
width: 32px;
121
height: 32px;
}
Complex selectors (e.g., deeply nested or universal selectors) are slower for
browsers to process. Writing more efficient selectors can improve rendering
performance.
● Keep selectors short and direct. Avoid overly specific selectors like
div.container ul li a span.
● Use class selectors (e.g., .btn-primary) instead of tag or descendant
selectors.
● Limit the use of universal selectors (*), as they affect every element on the
page.
Bad Example:
Good Example:
122
.link {
color: blue;
}
Repaint: Occurs when visual changes (like color) do not affect layout. Reflow:
Occurs when changes to layout (like resizing elements) cause the entire layout to
be recalculated.
● Minimize layout changes: Avoid using properties that cause reflows (e.g.,
width, height, top, left) frequently.
● Use CSS animations wisely: Prefer GPU-accelerated properties
(transform, opacity) over properties that cause reflows (top, left,
width).
/* Prefer */
.element {
transform: translateX(100px);
opacity: 0.5;
}
/* Avoid */
.element {
left: 100px;
123
}
GPU-Accelerated Properties
Certain CSS properties are hardware-accelerated, meaning they use the GPU to
render content more efficiently.
Start by designing for mobile devices and then progressively enhance for larger
screens using media queries. This ensures that your page is lightweight for
mobile users.
124
Mobile-First Example:
.container {
padding: 16px;
}
Use media queries to serve different styles, images, or fonts for mobile and
desktop. This prevents loading large assets on smaller screens.
What is will-change?
The will-change property hints to the browser which elements are likely to
change, allowing it to optimize their performance.
Use Sparingly:
125
.element {
will-change: transform;
}
What is Preloading?
Preloading tells the browser to load important resources (like critical CSS) as
soon as possible, without blocking other resources.
Lazy loading non-critical CSS files ensures that the page loads faster by
deferring unnecessary stylesheets until after the page has been fully rendered.
126
14. Optimize Fonts
Web fonts can significantly slow down page rendering. You can optimize them by
following these techniques:
● Use font-display: swap: This ensures that the text is displayed using
a fallback font until the web font has loaded.
@font-face {
font-family: 'MyFont';
src: url('myfont.woff2') format('woff2');
font-display: swap;
}
Conclusion
127
Thank you for joining me on this journey. Your time, curiosity, and dedication
mean the world to me. I hope this book has inspired you, expanded your
knowledge, and ignited your passion.
Keep learning, keep growing, and remember—great things are built one step at a
time.
Happy creating, and until next time—stay curious and keep coding!
Happy Coding!
Mehammed Teshome
128
129