0% found this document useful (0 votes)
127 views130 pages

CSS Handbook

Css hand book which made by the students of addis abeba university. Targeted for the developer and engineer.

Uploaded by

kalebmekonen.kb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
127 views130 pages

CSS Handbook

Css hand book which made by the students of addis abeba university. Targeted for the developer and engineer.

Uploaded by

kalebmekonen.kb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 130

CSS Handbook

by: Mohammed Teshome

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 What is CSS?

● Understanding how CSS works.


● Difference between HTML and CSS.

1.2 Syntax and Selectors

● CSS syntax (rules, properties, values).


● Selectors:
○ Universal (*), Type, Class, ID, Descendant, Child, Attribute,
Pseudo-classes (:hover, :nth-child), and Pseudo-elements
(::before, ::after).

1.3 Applying CSS

● Inline, Internal, and External CSS stylesheets.


● The concept of specificity and cascading rules.

1
1.4 CSS Units

● Relative Units: %, em, rem, vw, vh.


● Absolute Units: px, cm, mm, etc.

2. Box Model & Display

2.1 Box Model

● Margins, Padding, Borders, Content.


● How the box model affects layout and spacing.

2.2 Display Property

● block, inline, inline-block, none.


● Visibility: visible, hidden.

2.3 Sizing

● width, height, max-width, min-height, etc.

3. Layout Techniques

3.1 Positioning

● Static, Relative, Absolute, Fixed, and Sticky positioning.


● Understanding the stacking order (z-index).

2
3.2 Flexbox

● Flexible box layout for 1-dimensional layouts.


● Key properties: display: flex;, justify-content, align-items,
flex-direction, flex-wrap.
● Aligning and ordering items within a flex container.

3.3 CSS Grid

● 2-dimensional grid-based layouts.


● Key properties: grid-template-columns, grid-template-rows,
grid-area, gap, etc.
● Creating complex layouts using grid.

4. Styling Essentials

4.1 Typography

● Fonts: font-family, font-size, font-weight.


● Line height, text alignment (text-align), letter spacing, word spacing.
● Web-safe fonts and custom fonts using @font-face.

4.2 Colors and Backgrounds

● 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

● Borders: border-radius, border-style, border-width.


● Box shadows (box-shadow).
● Text shadows (text-shadow).

5. Responsive Design

5.1 Media Queries

● Creating responsive designs using @media.


● Breakpoints for different screen sizes (e.g., mobile, tablet, desktop).

5.2 Fluid Layouts

● Use of relative units like %, em, rem, vw, vh for fluid layouts.

5.3 Responsive Images

● Using max-width, object-fit, and picture elements.

6. Advanced CSS

6.1 Transitions and Animations

● Transitions: How to add smooth changes between states (e.g., hover


effects).

4
● Animations: Keyframes (@keyframes), animation properties for more
complex animations.

6.2 CSS Variables (Custom Properties)

● Declaring and using variables for reusability.

CSS code

:root {
--primary-color: #3498db;
}

h1 {
color: var(--primary-color);
}

6.3 Pseudo-elements and Pseudo-classes

● Advanced use of ::before, ::after, :hover, :nth-child, and other


selectors for styling.

6.4 CSS Functions

● calc(), min(), max(), clamp(): Dynamic calculations in CSS.

6.5 CSS Grid and Flexbox Combined

● Combining grid and flexbox to create complex, responsive layouts.

7. CSS Frameworks & Preprocessors

5
7.1 CSS Frameworks

● Bootstrap, Tailwind, Bulma, Foundation: Frameworks that provide


prebuilt components and responsive grids.

7.2 Preprocessors

● Sass, Less: CSS preprocessors that allow you to use features like
variables, nesting, and mixins to write more maintainable CSS.

8. CSS Architecture and Best Practices

8.1 BEM (Block, Element, Modifier)

● A naming convention for class names to write more readable and


maintainable CSS.

8.2 CSS Optimization

● Minifying CSS.
● Removing unused CSS (tree-shaking).

8.3 CSS-in-JS

● Writing CSS inside JavaScript (e.g., styled-components in React).

9. Performance Optimization and Best Practices

6
9.1 Reducing Repaints and Reflows

● Understanding how CSS can affect rendering and performance.

9.2 Critical Path CSS

● Loading essential CSS first to optimize page load.

9.3 Lazy Loading and Optimizing Images

● Optimizing images and resources for faster rendering and page


performance.

10. Keep Up-to-date

10.1 Browser Compatibility

● Using tools like Can I use to ensure browser compatibility.


● Applying fallbacks for unsupported features.

10.2 Learn Advanced Topics

● CSS Houdini: Low-level CSS APIs to control the style engine.


● CSS Subgrid: A new CSS grid feature that allows you to create nested
grids.

10.3 Stay Updated with New Features

● Follow CSS specifications to learn about upcoming features like Container


Queries,
() selector, etc.

7
Bonus: Projects for Practice

1. Simple landing page: Practice positioning, typography, and colors.


2. Responsive portfolio website: Use Flexbox and Grid to make it
responsive.
3. CSS animations gallery: Build a gallery to practice animations and
transitions.
4. Clone popular websites to better understand real-world layouts.
5. Implement a dashboard UI: Using CSS Grid and Flexbox to manage
complex layouts.

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

Let's dive into the basics of CSS step by step!

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;
}

● Selector: Targets the HTML element(s) you want to style.


● Property: The CSS attribute (e.g., color, font-size, margin) you want
to change.
● Value: The value for that attribute (e.g., blue, 16px, 10px).

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

There are three ways to apply CSS to your HTML file.

3.1 Inline CSS

You can apply styles directly to individual HTML elements using the style
attribute:

Example :

<h1 style="color: blue; font-size: 24px;">Hello World</h1>

3.2 Internal CSS

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>

3.3 External CSS

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.

4.1 Type Selector

Targets elements by their HTML tag name.

p {
color: red;
}

This will make all <p> elements red.

4.2 Class Selector

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.

<p id="special">This paragraph is special.</p>

CSS:

#special {
color: green;
}

4.4 Universal Selector

The * selector applies to all elements on the page.

* {
margin: 0;
padding: 0;
}

4.5 Descendant Selector

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;
}

5. CSS Box Model

Every element on a webpage is considered a rectangular box. The box model


consists of the following:

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.

6.1 Relative Units

● 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.

6.2 Absolute Units

17
● px (pixels): A fixed size in pixels.
● cm, mm: Centimeters, millimeters (rarely used in web design).

7. Styling Text and Fonts

7.1 Font Properties

● font-family: Specifies the font.


● font-size: Specifies the size of the font.
● font-weight: Specifies the thickness of the font (normal, bold, lighter,
or numerical values like 400).

p {
font-family: Arial, sans-serif;
font-size: 16px;
font-weight: bold;
}

7.2 Text Alignment

● text-align: Aligns text (e.g., left, center, right).

h1 {
text-align: center;
}

8. Color and Background

18
8.1 Color

You can set colors using keywords, hex codes, RGB, or HSL.

● Color keyword: color: blue;


● Hex code: color: #3498db;
● RGB: color: rgb(52, 152, 219);
● HSL: color: hsl(207, 70%, 53%);

8.2 Backgrounds

You can set the background color or image of an element:

div {
background-color: #f0f0f0;
background-image: url('background.jpg');
background-size: cover;
}

9. CSS Margins and Padding

9.1 Margins

The margin clears space outside the element's border.

p {
margin: 20px; /* Adds a 20px margin to all sides */
}

You can also set specific margins:

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;
}

You can also set specific paddings:

div {
padding-top: 10px;
padding-right: 15px;
padding-bottom: 10px;
padding-left: 5px;
}

10. Border

You can add borders to elements.

div {
border: 2px solid black;

20
border-radius: 10px; /* Makes the corners round */
}

11. Shorthand Properties

CSS allows you to shorten multiple properties into one line.

● Margin and Padding Shorthand:

p {
margin: 10px 20px 10px 20px; /* top, right, bottom, left */
}

● Font Shorthand:

p {
font: bold 16px Arial, sans-serif;
}

3. CSS Box Model


The box model is fundamental to understanding how elements are rendered on
a webpage. It represents how the browser calculates the size of elements.

21
Components of the Box Model:

Each element on a webpage is essentially a box, and the box model consists of
four parts:

1. Content: The actual content of the element (text, images, etc.).


2. Padding: Space between the content and the border. Increases the size of
the element.
3. Border: A line around the element's padding (optional).
4. Margin: Space outside the border. Creates distance between the element
and other elements.

Here's a visual representation:

Box Model Properties:

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 */
}

Or, set specific 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 */
}

You can set margins for each side:

div {
margin: 20px; /* Adds 20px margin on all sides */
}

div {
margin-top: 10px;
margin-right: 15px;

24
margin-bottom: 10px;
margin-left: 5px;
}

Box Model Calculation

The total width and height of an element are calculated as:

● Total Width = content width + padding-left + padding-right +


border-left + border-right + margin-left + margin-right
● Total Height = content height + padding-top + padding-bottom
+ border-top + border-bottom + margin-top + margin-bottom

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.

2.1 Block-Level Elements

Elements like <div>, <p>, and <h1> are block-level elements. Block-level
elements:

● Take up the full width of their parent container.


● Always start on a new line.

div {
display: block;
}

Example:

26
<div>This is a block element</div>
<div>This will appear on a new line</div>

2.2 Inline-Level Elements

Elements like <span>, <a>, and <strong> are inline elements. Inline elements:

● Only take up as much width as their content.


● Stay on the same line as surrounding content.

span {
display: inline;
}

Example:

<p>This is <span>inline</span> text.</p>

2.3 Display: None

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>

2.4 Display: Inline-Block

inline-block combines features of both block and inline elements:

● 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:

<p>This is <span>inline-block</span> text.</p>

2.5 Display: Flex

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>

2.6 Display: Grid

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

1. CSS Display Property

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.

Examples: <div>, <p>, <h1>, <section>, etc.

Css code

.block-element {
display: block;
width: 100%;
background-color: lightblue;
}

html code

<div class="block-element">This is a block-level element.</div>

34
display: inline;

● Inline elements do not start on a new line and only take up as much width
as necessary.

Examples: <span>, <a>, <strong>, etc.


Css code

.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.

Combines characteristics of both inline and block elements.


Css code

.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

The position property in CSS is used to control the placement of elements on


the web page. It determines how an element is positioned relative to its parent
element, other elements, or the viewport. Understanding the different values of
the position property is key to creating dynamic and flexible layouts.

36
Here's a comprehensive guide:

1. position: static;

● Default Value: Every element is positioned according to the normal


document flow (meaning it just appears where it naturally would).
● Characteristics:
○ The element is not affected by the top, right, bottom, or left
properties.
○ It does not change the element's position from where it would
naturally appear in the document.

Css code

37
.static-box {
position: static;
background-color: lightgrey;
}

Html code

<div class="static-box">This is a static positioned


element.</div>

2. position: relative;

● Relative to Itself: The element is positioned relative to its normal position.


● Characteristics:
○ The element's original space is still preserved in the document flow.
○ You can use the top, right, bottom, and left properties to
adjust its position relative to where it would have been.

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;

● Relative to the Nearest Positioned Ancestor: The element is positioned


relative to the nearest ancestor that has a position other than static. If
there is no such ancestor, it will be positioned relative to the initial
containing block (usually the <html> element).
● Characteristics:
○ The element is removed from the normal document flow.
○ You can use the top, right, bottom, and left properties to place
the element precisely where you want it within the containing block.

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;

● Relative to the Viewport: The element is positioned relative to the


browser window (viewport), so it stays in the same place even when the
page is scrolled.
● Characteristics:
○ The element is removed from the normal document flow.
○ It doesn't move when you scroll the page.
○ Commonly used for sticky headers, footers, or floating buttons.

Css code

.fixed-box {
position: fixed;
bottom: 10px;
right: 10px;
background-color: lightgreen;
padding: 20px;

40
}

Html code

<div class="fixed-box">This is a fixed positioned element.</div>

5. position: sticky;

● Combination of Relative and Fixed: The element is treated as


relative until it reaches a certain point in the viewport, at which point it
"sticks" and behaves as fixed.
● Characteristics:
○ The element toggles between relative and fixed positioning
depending on the user's scroll position.
○ Useful for sticky headers or sidebars.

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

<div class="box1">Box 1</div>


<div class="box2">Box 2</div>

Summary of position Property:

● static: Default value. Elements are positioned according to the normal


document flow.
● relative: Elements are positioned relative to their original position.
● absolute: Elements are positioned relative to the nearest positioned
ancestor.
● fixed: Elements are positioned relative to the viewport and do not move on
scroll.
● sticky: Elements switch between relative and fixed positioning based on
scroll position.

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:

1. Basic Concepts of 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.

2. Setting Up a Flex Container

To start using Flexbox, you need to define a 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>

3. Flexbox Properties for the Container

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

Aligns the flex items along the main axis.

● 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 */
}

4. Flexbox Properties for the Items

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

Basic Flexbox Example

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>

Responsive Flexbox Layout

.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

● Flexbox provides a simple and powerful way to create complex layouts


without relying heavily on floats or positioning.
● By understanding and mastering the properties associated with Flexbox,
you can build responsive and adaptive web designs more efficiently

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.

Item: The child elements inside a grid container.


css
Copy code
.item {
grid-column: span 2;
grid-row: span 1;
}


○ 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;
}

Example Layout Using Flexbox

Here's an example of a simple layout using Flexbox:

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.

Let’s walk through the essential components of CSS styling:

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;
}

ID Selector: Targets a specific element with an ID.

#header {
font-size: 24px;
}

Universal Selector: Targets all elements.

* {
margin: 0;
padding: 0;
}

Attribute Selector: Targets elements based on the presence or value of an


attribute.

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);
}

RGBA (with Alpha for Transparency):

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

Typography controls the appearance of text on a webpage.

Common Text Properties:


Font-Family: Specifies the font type.

body {
font-family: 'Arial', sans-serif;
}

Font-Size: Sets the size of the font.

h1 {
font-size: 32px;
}

67
Font-Weight: Specifies the thickness of the font.

p {
font-weight: bold;
}

Line-Height: Controls the space between lines of text.

p {
line-height: 1.5;
}

Text-Align: Aligns the text within an element.

p {
line-height: 1.5;
}

h2 {
text-align: center;
}

Text-Decoration: Adds an underline, line-through, or overline to text.

a {
text-decoration: none;
}

Text-Transform: Changes the capitalization of text.

h1 {

68
text-transform: uppercase;
}

4. Backgrounds

You can style an element's background using various properties.

Common Background Properties:


Background-Color: Sets the background color of an element.

body {
background-color: lightyellow;
}

Background-Image: Adds an image as the background.

div {
background-image: url('background.jpg');
}

Background-Repeat: Controls whether the background image is repeated.

div {
background-repeat: no-repeat;
}

Background-Position: Sets the position of the background image.

69
div {
background-repeat: no-repeat;
}
div {
background-position: center;
}

Background-Size: Controls the size of the background image.


css
Copy code
div {
background-size: cover; /* Scale the background to cover
the container */
}

5. Spacing (Padding & Margin)

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 */
}

You can apply different values for each side:

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;
}

border-radius: Adds rounded corners to the border.

71
div {
border-radius: 10px;
}

7. Width and Height

Setting width and height controls the size of elements.

Width: The horizontal size of the element.

div {
width: 100px;
}

Height: The vertical size of the element.

div {
height: 200px;
}

You can use different units:

● 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.

block: Takes up the full width and starts on a new line.

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.

visible: The element is visible (default).

p {
visibility: visible;
}

hidden: The element is invisible but still occupies space.

p {
visibility: hidden;
}

10. Box Shadow

Add shadows to elements using the box-shadow property.

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.

Values range from 0 (completely transparent) to 1 (completely opaque).

div {
opacity: 0.7;
}

12. Cursor

The cursor property changes the mouse pointer when hovering over an element.

pointer: Displays a hand cursor (often used for clickable elements).

a {
cursor: pointer;
}

default: The default cursor.

div {
cursor: default;
}

13. Transition and Animation

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;
}

Summary of Styling Essentials:

1. Selectors: Target HTML elements for styling.


2. Colors: Set background, text, and border colors.

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.

By mastering these essentials, you'll be able to style modern web pages


effectively.

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 (Using Relative Units like %, em, rem)


2. Media Queries
3. Flexible Images (Fluid Images and Image Breakpoints)
4. Responsive Typography
5. CSS Flexbox and Grid

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.

Fixed Layout (Not Responsive):

78
.container {
width: 600px; /* Fixed width, doesn't adapt to different
screens */
}

Fluid Layout (Responsive):

.container {
width: 80%; /* Width changes according to screen size */
}

Relative Units:

● em: Relative to the font size of the nearest parent element.


● rem: Relative to the root font size (html).
● %: Relative to the containing element.

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:

@media only screen and (max-width: 768px) {


/* Styles for screens with width less than 768px */

79
.container {
width: 100%;
}
}

Example of Media Queries for Different Breakpoints:

/* Default (for larger screens like desktops) */


.container {
width: 80%;
}

/* Tablets (widths between 768px and 1024px) */


@media only screen and (max-width: 1024px) {
.container {
width: 90%;
}
}

/* Mobile phones (widths less than 768px) */


@media only screen and (max-width: 768px) {
.container {
width: 100%;
}
}

Common Breakpoints:

● Desktop: > 1024px


● Tablet: 768px - 1024px
● Mobile: < 768px

80
3. Flexible Images

Images should be responsive, so they scale with the size of the screen rather
than having a fixed width.

Responsive Image Example:

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

Typography needs to scale based on screen size to ensure readability.

Using em or rem for Font Sizes:

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 */
}

@media only screen and (max-width: 768px) {


body {
font-size: 14px; /* Smaller font size for mobile */
}
}

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 */
}

5. Flexbox for Responsive Layout

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.

Basic Flexbox Layout:

.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;
}

@media only screen and (max-width: 768px) {


.item {
flex: 1 1 100%; /* Flex items take up 100% of the
container's width on mobile */
}
}

6. CSS Grid for Responsive Layout

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.

Basic Grid Example:

.container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* 3 equal-width
columns */
gap: 20px;
}

@media only screen and (max-width: 768px) {

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%;
}

/* Tablet and larger styles */


@media only screen and (min-width: 768px) {
.container {
width: 80%;
}
}

/* 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.

Example with Bootstrap:

Bootstrap uses a grid system with responsive breakpoints:

<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>

● col-md-6: Column takes up 6 grid spaces on medium screens.


● col-lg-4: Column takes up 4 grid spaces on large screens.

Summary of Responsive Design Techniques

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.

By mastering these techniques, you'll be able to create responsive web designs


that work well across all devices!

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:

1. CSS Preprocessors (Sass, LESS)

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;
}

Nesting: Write cleaner, hierarchical CSS by nesting selectors.


scss code

nav {
ul {
list-style: none;
li {
display: inline-block;
}
}
}

Mixins: Reuse blocks of CSS with arguments to avoid repetition.


Scss code:

@mixin button-style($color) {
background-color: $color;
padding: 10px;
border-radius: 5px;
}

.btn-primary {
@include button-style(#3498db);
}

2. CSS Custom Properties (CSS Variables)

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;
}

Use the Variable:

body {
color: var(--primary-color);
}

● The Power of Custom Properties:


○ They can be changed at runtime with JavaScript.
○ They cascade, meaning they can be redefined within specific
elements or media queries.

3. CSS Grid (Advanced Techniques)

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.

Named Grid Areas:


Example :

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 */
}

Grid Line Numbering:

.item {
grid-column: 1 / 3; /* Span from column line 1 to 3 */
grid-row: 1 / 2; /* Span from row line 1 to 2 */
}

4. CSS Flexbox (Advanced Techniques)

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:

@media (max-width: 768px) {


.container {
flex-direction: column; /* Stack items vertically on
small screens */
}
}

5. CSS Animations and Transitions

CSS animations and transitions allow you to add dynamic, interactive elements
to your design.

Transitions: Smoothly change property values when something changes (like


hover or click).

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 */
}

Keyframe Animations: Define multiple states of an element over time.


Example :

@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.

6. CSS Transforms (2D & 3D)

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 */
}

7. CSS Clip Path

The clip-path property allows you to create complex shapes by clipping an


element.

Clip Path Example:

.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 */
}

8. CSS Pseudo-Classes and Pseudo-Elements

Pseudo-classes and pseudo-elements allow you to style elements based on their


state or insert content dynamically.

● 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;
}

9. Responsive Design (Advanced Techniques)

Responsive design doesn’t just involve media queries but also thinking about
how your layout and components adapt in terms of flexibility and scalability.

Container Queries (Newer in CSS): Container queries adjust styles based on


the size of an element's container instead of the viewport, offering more granular
control.

@container (min-width: 600px) {


.card {
display: flex;
}
}

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

Attribute Selectors: Style elements based on attributes.

a[href^="https"] {
color: green; /* Style links that start with https */
}

General Sibling Selector:

h1 ~ p {
color: blue; /* Style all p elements that are siblings of h1
*/
}

() Pseudo-Class: Exclude certain elements from being selected.

p:not(.highlight) {
color: gray; /* Style all p elements except those with the
class "highlight" */
}

11. CSS Variables and Calc() Function

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 */
}

12. Custom Fonts and Icon Fonts

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.

9. CSS Frameworks & Preprocessors


Learning CSS frameworks and preprocessors allows you to speed up your
workflow, write more maintainable and scalable code, and build sophisticated,
responsive designs with ease. Here's a breakdown of both CSS frameworks and
preprocessors:

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.

Grid System: Bootstrap’s grid is based on a 12-column system, which makes


building responsive layouts easy.

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>

Prebuilt Components: Bootstrap includes a wide range of prebuilt components


like buttons, cards, and modals.

<button class="btn btn-primary">Primary Button</button>

● Responsive Design: Bootstrap is mobile-first and responsive by default. It


uses media queries to adjust the layout across devices.

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.

<div class="text-center bg-blue-500 text-white p-4">


This is a Tailwind element
</div>

Responsive Design: Tailwind makes it easy to create responsive designs by


using prefixes like sm:, md:, lg:, and xl:.

<div class="bg-blue-500 lg:bg-green-500">Responsive

100
Background</div>

● Customization: Tailwind is highly customizable. You can extend its


configuration to change colors, spacing, and more.

3. Foundation

Foundation by Zurb is another responsive front-end framework similar to


Bootstrap but with more flexibility in customization.

Responsive Grid: Foundation uses a flexible grid system to create responsive


layouts.

<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>

Components: Like Bootstrap, Foundation offers pre-built UI components such as


buttons, forms, navigation, and modals.

<button class="button">Foundation Button</button>

4. Bulma

Bulma is a modern CSS framework based on Flexbox. It is lightweight and


simple to use with a modular structure.

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.

<p class="is-size-4 has-text-centered">Centered Text</p>

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.

1. Sass (Syntactically Awesome Stylesheets)

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';

2. LESS (Leaner Style Sheets)

LESS is another CSS preprocessor that is similar to Sass but with slightly
different syntax and features.

Variables: LESS variables are defined using @.

@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

Nesting: Nesting is also supported in Stylus.

nav
ul
list-style none
li

105
display inline-block

Functions: Stylus supports functions to compute values dynamically.

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)

Choosing Between Frameworks and Preprocessors

● 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.

Combining Frameworks and Preprocessors

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.

// Custom Bootstrap variables


$primary-color: #3498db;

@import 'bootstrap'; // Import Bootstrap's styles with your


customizations

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.

1. CSS Architecture Concepts

1.1 Separation of Concerns

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

● Modular CSS means breaking down styles into smaller, reusable


components. This allows for better maintainability and scalability.
○ Example: Separating your button styles into a reusable component
that can be applied across different parts of the website.

1.3 Reusability

● Reusability refers to writing CSS code that can be applied in multiple


places without duplication. This reduces the overall size of your stylesheets
and avoids redundancy.

2. Best Practices in CSS Architecture

2.1 Organize CSS Files

File Structure

Maintaining a well-structured file organization makes your CSS easier to navigate


and manage.

Example 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

2.2 Use a Naming Convention

BEM (Block Element Modifier)

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.

● Block: The outermost component (e.g., navbar).


● Element: A child component of the block (e.g., navbar__item).
● Modifier: A variant of the block or element (e.g.,
navbar__item--active).

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>

OOCSS (Object-Oriented CSS)

OOCSS aims at separating structure from appearance to promote reusable code.

● Structure: Defines how elements are laid out (e.g., .card).


● Skin: Defines the visual appearance (e.g., .card--primary).

Example:

<div class="card card--primary">


<h3 class="card__title">Title</h3>
</div>

2.3 Avoid Deep Nesting

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
}

2.4 DRY (Don’t Repeat Yourself)

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;
}

2.5 Use Variables

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;
}

2.6 Leverage Utility Classes

Utility-first CSS frameworks like Tailwind CSS promote using small,


single-purpose classes for layout, spacing, colors, etc. Utility classes are easier
to maintain and reuse.

Example:

<div class="p-4 bg-blue-500 text-white">Button</div>

2.7 Use Meaningful Class Names

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

3.1 BEM (Block Element Modifier)

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>

3.2 SMACSS (Scalable and Modular Architecture for CSS)

SMACSS organizes CSS into five categories: Base, Layout, Module, State, and
Theme.

● Base: Default styles, like resets or global elements.


● Layout: Structural elements, like headers, footers, and sidebars.
● Module: Individual components, like buttons or cards.
● State: Specific states for components (e.g., .is-active).

114
● Theme: Theme-specific changes.

3.3 Atomic CSS

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:

<div class="bg-blue text-white p-4">Styled Box</div>

Atomic CSS is similar to utility-first frameworks like Tailwind CSS.

4. CSS Optimization

4.1 Minify CSS

Minifying CSS reduces file size by removing whitespace, comments, and


unnecessary characters, leading to faster load times.

● Use tools like CSSNano or CleanCSS to minify your CSS.

4.2 Lazy Loading & Critical CSS

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.

● Use tools like Critical to extract critical CSS.

115
4.3 Avoid Inline Styles

Avoid using inline styles unless absolutely necessary, as they increase specificity
and reduce reusability.

4.4 Remove Unused CSS

Tools like PurgeCSS can analyze your HTML and remove unused CSS, reducing
the size of your final stylesheet.

● PurgeCSS is particularly useful when working with utility-first frameworks


like Tailwind CSS.

5. CSS Performance

5.1 Reduce Specificity

● Avoid highly specific selectors (e.g., div ul li a). Instead, use


class-based selectors to reduce specificity battles and improve
maintainability.

5.2 Use CSS Grid and Flexbox Wisely

● 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.

5.3 Optimize for Mobile

116
● Use media queries and a mobile-first approach to create responsive
designs.

Mobile-first Example:

.button {
padding: 8px;
}

@media (min-width: 768px) {


.button {
padding: 12px;
}
}

5.4 Use Hardware-Accelerated Transitions

● 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

By following CSS architecture principles, using best practices like modularity,


naming conventions, and optimization techniques, and leveraging CSS
methodologies like BEM and SMACSS, you can write clean, maintainable, and
scalable CSS that performs well and is easy to extend over time. These
principles are essential, especially in large-scale projects or when working in
teams.

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?

Minification involves removing unnecessary characters (like spaces, newlines,


and comments) from your CSS files to reduce their size without affecting
functionality. This leads to faster download times and improved page
performance.

How to Minify:

● Use tools like CSSNano or CleanCSS to minify CSS during development.


● For larger projects, integrate minification into your build process using task
runners like Gulp or Webpack.

2. Reduce HTTP Requests

Combine CSS Files

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.

3. Use Critical CSS

What is Critical CSS?

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.

How to Implement Critical CSS:

● Extract critical CSS using tools like Critical.


● Inline the critical CSS in the <head> of your HTML, while deferring the
loading of the rest of your CSS.

<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.

How to Remove Unused CSS:

● 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

npx purgecss --css styles.css --content index.html

Be Cautious with Frameworks:

CSS frameworks like Bootstrap or Tailwind CSS include a large number of


utility classes, many of which may not be used. Tools like PurgeCSS can help
reduce this bloat.

5. Optimize CSS Delivery

Asynchronous CSS Loading

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:

<link rel="stylesheet" href="styles.css" media="print"


onload="this.media='all'">

Media Queries for Non-Critical CSS

Defer loading of non-critical CSS (like print styles) using media queries:

<link rel="stylesheet" href="print-styles.css" media="print">

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.

How CSS Sprites Work:

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;
}

7. Use Efficient Selectors

Why Selector Efficiency Matters

Complex selectors (e.g., deeply nested or universal selectors) are slower for
browsers to process. Writing more efficient selectors can improve rendering
performance.

Best Practices for Selectors:

● 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:

body div.container ul li a span {


color: blue;
}

Good Example:

122
.link {
color: blue;
}

8. Reduce Repaints and Reflows

Understanding Repaints and Reflows

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.

Best Practices to Avoid Reflows:

● 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
}

9. Leverage Hardware Acceleration

GPU-Accelerated Properties

Certain CSS properties are hardware-accelerated, meaning they use the GPU to
render content more efficiently.

Use transform and opacity:

Animations involving transform and opacity are handled by the GPU,


resulting in smoother performance.

/* Smooth transition using GPU */


.element {
transform: translateZ(0);
opacity: 0.8;
}

10. Optimize CSS for Mobile

Use a Mobile-First Approach

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;
}

@media (min-width: 768px) {


.container {
padding: 32px;
}
}

Responsive Images and Fonts

Use media queries to serve different styles, images, or fonts for mobile and
desktop. This prevents loading large assets on smaller screens.

11. Use will-change Property Wisely

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:

Overusing will-change can cause memory bloat, so apply it only when


necessary.

125
.element {
will-change: transform;
}

12. Preload Key CSS Files

What is Preloading?

Preloading tells the browser to load important resources (like critical CSS) as
soon as possible, without blocking other resources.

<link rel="preload" href="main.css" as="style">

13. Lazy Load Non-Critical CSS

Lazy loading non-critical CSS files ensures that the page loads faster by
deferring unnecessary stylesheets until after the page has been fully rendered.

How to Lazy Load CSS:

You can use JavaScript to lazy load additional stylesheets.

let link = document.createElement('link');


link.rel = 'stylesheet';
link.href = 'additional-styles.css';
document.head.appendChild(link);

126
14. Optimize Fonts

Web fonts can significantly slow down page rendering. You can optimize them by
following these techniques:

Font Loading Strategies:

● 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

By following these performance optimization techniques and best practices, you


can ensure that your CSS is efficient, maintainable, and optimized for a
fast-loading, responsive web experience. Optimized CSS directly enhances user
experience, search engine ranking, and overall website performance.

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.

For any message, feel free to reach out to me at: 0923191253

Happy creating, and until next time—stay curious and keep coding!

Happy Coding!
Mehammed Teshome

128
129

You might also like