0% found this document useful (0 votes)
3 views103 pages

CSS Notes

CSS (Cascading Style Sheets) is a stylesheet language that defines the presentation of HTML documents, allowing for separation of design and structure, consistency, and efficiency in web development. It can be applied in three main ways: inline, internal, and external CSS, with external CSS being the best practice for scalability and maintainability. CSS selectors target HTML elements for styling, with various types including descendant, child, sibling, pseudo-classes, and attribute selectors, providing flexibility in design.

Uploaded by

mutisya546
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)
3 views103 pages

CSS Notes

CSS (Cascading Style Sheets) is a stylesheet language that defines the presentation of HTML documents, allowing for separation of design and structure, consistency, and efficiency in web development. It can be applied in three main ways: inline, internal, and external CSS, with external CSS being the best practice for scalability and maintainability. CSS selectors target HTML elements for styling, with various types including descendant, child, sibling, pseudo-classes, and attribute selectors, providing flexibility in design.

Uploaded by

mutisya546
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

Cascading Stylesheets (CSS)

Notes

2025
1. Introduction to CSS

What is CSS?

CSS (Cascading Style Sheets) is a stylesheet language used to describe the presentation (look
and feel) of an HTML document. While HTML handles the structure and content of a webpage,
CSS defines how that content appears—including colors, fonts, spacing, layout, animations, and
responsiveness.

Example

<p>Hello, world!</p>

Using CSS, we can style it:

p {
color: blue;
font-size: 20px;
}

Why CSS is Important

• Separation of concerns: Keeps design (CSS) separate from structure (HTML).


• Consistency: Apply the same style across multiple pages easily.
• Efficiency: Make global changes by editing just one file.
• Responsiveness: Create adaptable designs for desktops, tablets, and phones.

CSS in Modern Web Development

Modern development uses CSS alongside frameworks like Flexbox, Grid, Bootstrap, Tailwind,
and preprocessors like SASS/SCSS, enabling faster and more maintainable styling.

How CSS Works with HTML

CSS targets HTML elements using selectors, then applies rules (declarations) that define how
those elements should appear.

CSS Rule Structure:

selector {
property: value;
}

Example:

h1 {
SOMATECH IT – 0726 674 946 2
color: green;
text-align: center;
}

This changes all <h1> elements to green and centers them.

Types of CSS

1. Inline CSS

CSS written directly within an HTML tag using the style attribute.
Good for testing, not recommended for production.

<h1 style="color:red;">Inline CSS Example</h1>

2. Internal CSS

CSS written in the <head> of an HTML document using <style> tags.


Good for small projects or demos.

<head>
<style>
body {
background-color: #f0f0f0;
}
</style>
</head>

3. External CSS

CSS written in a separate file (e.g., [Link]) and linked to HTML using <link>.
Best practice for real-world projects.

<head>
<link rel="stylesheet" href="[Link]" />
</head>

How the "Cascading" Works

"Cascading" means that the order of CSS rules matters. When multiple rules target the same
element:

1. Inline CSS wins over Internal and External.


2. More specific selectors override general ones.

SOMATECH IT – 0726 674 946 3


3. Later rules override earlier ones if they have the same specificity.

Summary

Feature Description
Full Form Cascading Style Sheets
Purpose Styling and visual formatting of HTML documents
Location Inline, Internal, External
Options
Modern Use Focus on external CSS, use of frameworks and media queries
Best Practice Separate CSS from HTML, use semantic naming, and keep code clean and
reusable

2. Ways to Apply CSS


CSS can be applied to HTML documents in three main ways. Each has its strengths and ideal use
cases. Understanding when and how to use each method is essential for clean, scalable, and
professional web development.

1. Inline CSS
What is it?
Inline CSS is written inside an HTML element using the style attribute.
Use Case:
• For quick testing or styling a single element temporarily.
• Not recommended for large projects due to poor scalability and maintainability.

Example:

<h2 style="color: crimson; text-align: center;">Welcome to


CSS</h2>

2. Internal CSS (Embedded CSS)

What is it?

Internal CSS is written within a <style> tag inside the <head> of an HTML document. The
styles apply to that specific HTML file only.

Use Case:

• For single-page websites, prototypes, or learning purposes.


• Easier to manage than inline CSS but not suitable for multi-page sites.

SOMATECH IT – 0726 674 946 4


Example:

<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: #f9f9f9;
font-family: Arial, sans-serif;
}

h1 {
color: steelblue;
}
</style>
</head>
<body>
<h1>Internal CSS Example</h1>
</body>
</html>

3. External CSS

What is it?

External CSS is stored in a separate .css file, and linked to the HTML document using the
<link> tag in the <head> section.

Use Case

• Ideal for real projects, multi-page websites, and collaborative development.


• Promotes separation of concerns and better performance (CSS can be cached).

Example:

HTML file ([Link]):

<head>
<link rel="stylesheet" href="[Link]">
</head>

External file ([Link])

body {
background-color: #ffffff;
SOMATECH IT – 0726 674 946 5
font-family: 'Segoe UI', sans-serif;
}

h1 {
color: darkgreen;
}

Comparison Table

Method Location Scope Maintainability Use Case


Inline CSS Inside HTML Single Poor Quick fixes, demos
tags element
Internal CSS Inside <head> Single page Fair One-page apps, tests
External Separate file Entire website Best All professional
CSS projects

Best Practice Summary

• Always prefer external CSS for scalability and team projects.


• Avoid using inline CSS in production — makes code harder to read and manage.
• Internal CSS is fine for demos, tutorials, or one-off pages.

3. CSS Syntax & Selectors

CSS selectors are used to target HTML elements that you want to style. The syntax consists of a
selector and declaration block.

Basic CSS Syntax:

selector {
property: value;
}

• Selector: This specifies the HTML element(s) you want to apply styles to.
• Property: This defines the CSS property you want to style, like color, font-size, or
margin.
• Value: This is the value assigned to the CSS property, like red, 16px, or 10px.

For example:

h1 {
color: blue;
font-size: 24px;

SOMATECH IT – 0726 674 946 6


}

In this example, the h1 selector is used to target all <h1> elements and apply the color blue and
the font size 24px.

Types of Selectors

• Universal selector (*): Targets all elements on the page.

* {
color: red;
}

• Element selector (p): Targets all <p> (paragraph) elements.

p {
font-size: 16px;
}

• ID selector (#id): Targets an element with a specific id attribute. The # symbol is used
to denote an ID selector.

#main-header {
text-align: center;
}

• Class selector (.class): Targets elements with a specific class attribute. The . symbol
is used for class selectors.

.important-text {
font-weight: bold;
}

• Grouping selectors: You can group multiple selectors together to apply the same styles to
different elements.

h1, h2, h3 {
color: green;
}

Advanced Selectors

1. Descendant and Child Selectors

SOMATECH IT – 0726 674 946 7


These selectors allow you to target elements based on their relationship to other elements in the
HTML structure. Both descendant and child selectors are used to style elements nested inside
other elements, but they differ in their specificity and application.

• Descendant Selector (space between selectors): Targets elements that are nested within
another element, no matter how deeply they are nested.

Syntax:

parent descendant {
property: value;
}

Example:

div p {
color: blue;
}

Effect: This will select all <p> elements inside a <div>, regardless of how deeply they
are nested within the <div>.

HTML example:

<div>
<p>This is a paragraph inside a div.</p>
<div>
<p>This is another paragraph inside a nested div.</p>
</div>
</div>

• Child Selector (>): Targets direct child elements of a specified parent element. The child
selector is more specific, as it only selects elements that are direct children (not deeply
nested).

Syntax:

parent > child {


property: value;
}

Example:

div > p {
color: green;
}

SOMATECH IT – 0726 674 946 8


Effect: This will select only the <p> elements that are direct children of a <div>
element.

HTML example:

<div>
<p>This is a direct child paragraph of the div.</p>
<div>
<p>This is a nested paragraph, it will not be
selected.</p>
</div>
</div>

2. Sibling Selectors

Sibling selectors target elements that share the same parent. They allow you to select elements that
are either immediately adjacent or any subsequent siblings of a specific element.

• Adjacent Sibling Selector (+): Targets the element immediately following a specified
element.

Syntax:

element1 + element2 {
property: value;
}

Example:

h2 + p {
color: red;
}

Effect: This will select the <p> element that immediately follows an <h2> element. The
<p> must be the next sibling in the HTML structure.

HTML example:

<h2>Section Title</h2>
<p>This paragraph will be selected, as it immediately follows
the h2 element.</p>
<p>This paragraph will not be selected, because it is not
immediately after the h2.</p>

• General Sibling Selector (~): Targets all elements that are siblings of a specified element,
not just the immediately adjacent one.

SOMATECH IT – 0726 674 946 9


Syntax:

element1 ~ element2 {
property: value;
}

Example:

h2 ~ p {
color: purple;
}

Effect: This will select all <p> elements that are siblings of an <h2> element, regardless
of how many elements come between them.

HTML example:

<h2>Section Title</h2>
<p>This paragraph will be selected.</p>
<p>This paragraph will also be selected.</p>

3. Pseudo-classes

Pseudo-classes are special selectors used to style elements based on their state or position within
the document structure. They allow you to apply styles to elements in specific conditions.

• :hover: Applies styles to an element when the user hovers over it with the mouse.

Syntax:

element:hover {
property: value;
}

Example:

a:hover {
color: red;
text-decoration: underline;
}

Effect: This changes the color of a link to red and underlines it when the user hovers the
mouse pointer over the link.

HTML example:

SOMATECH IT – 0726 674 946 10


<a href="#">Hover over me!</a>

• :first-child: Targets the first child element within a parent.

Syntax:

parent:first-child {
property: value;
}

Example:

ul li:first-child {
font-weight: bold;
}

Effect: This will apply a bold font style to the first <li> (list item) in every <ul>
(unordered list).

HTML example:

<ul>
<li>First Item</li>
<li>Second Item</li>
</ul>

4. Pseudo-elements

Pseudo-elements are used to style specific parts of an element that can’t be targeted directly. They
allow you to style content that doesn't exist in the DOM but is generated by CSS.

• ::before: Adds content before an element's original content.

Syntax:

element::before {
content: "Text to appear before the element";
}

Example:

p::before {
content: "Note: ";
font-weight: bold;
}

SOMATECH IT – 0726 674 946 11


Effect: This will add the text "Note: " before the content of each <p> element.

HTML example:

<p>This is a paragraph.</p>

• ::after: Adds content after an element's original content.

Syntax:

element::after {
content: "Text to appear after the element";
}

Example:

p::after {
content: " (End of paragraph)";
font-style: italic;
}

Effect: This will append the text " (End of paragraph)" after each <p> element.

HTML example:

<p>This is a paragraph.</p>

Summary of Selectors

Selector Type Description Example


Descendant Selects elements nested within div p {color: blue;}
Selector another element, regardless of
depth.
Child Selector Selects direct children of a div > p {color: green;}
specified element.
Adjacent Sibling Selects the element immediately h2 + p {color: red;}
after a specified element.
General Sibling Selects all sibling elements after a h2 ~ p {color: purple;}
Selector specified element.
Pseudo-class Selects elements when hovered a:hover {color: red;}
:hover by the user.
Pseudo-class Selects the first child element of a ul li:first-child {font-
:first-child parent. weight: bold;}
Pseudo-element Adds content before the element's p::before {content:
::before original content. "Note: ";}

SOMATECH IT – 0726 674 946 12


Pseudo-element Adds content after the element's p::after {content: "
::after original content. (End of paragraph)";}

These selectors allow you to target and style elements based on their structure, position, and user
interaction, adding a lot of flexibility and power to your CSS styling.

Attribute Selectors

Attribute selectors in CSS allow you to target HTML elements based on the presence or value of
an attribute. This can be incredibly useful for styling elements that share certain attributes without
needing to rely on classes or IDs.

Basic Syntax:

element[attribute] {
property: value;
}

• element: The HTML element you want to target (e.g., input, a, div).
• attribute: The name of the attribute you want to target.
• property: value;: The CSS property and value you want to apply to the selected
element.

Types of Attribute Selectors

1. [attribute]: Targets all elements that have the specified attribute, regardless of its value.

Syntax:

element[attribute] {
property: value;
}

Example:

a[href] {
color: blue;
}

Explanation: This will apply the color blue to all <a> elements that have an href
attribute, regardless of the href's value. Essentially, it selects all links.

HTML example:

<a href="[Link] here</a>


<a>No link</a>

SOMATECH IT – 0726 674 946 13


2. [attribute="value"]: Targets elements with a specific attribute that has an exact value.

Syntax:

element[attribute="value"] {
property: value;
}

Example:

input[type="text"] {
background-color: yellow;
}

Explanation: This will style all <input> elements that have a type="text" attribute,
applying a yellow background color.

HTML example:

<input type="text" placeholder="Enter text">


<input type="password" placeholder="Enter password">

3. [attribute~="value"]: Selects elements with an attribute whose value is a list of words,


one of which matches the specified value. It is commonly used for selecting classes or
multi-word attributes.

Syntax:

element[attribute~="value"] {
property: value;
}

Example:

p[class~="highlight"] {
color: red;
}

Explanation: This will select all <p> elements whose class attribute contains the word
"highlight" (as part of a space-separated list of classes).

HTML example:

<p class="highlight important">This is a highlighted


paragraph.</p>
<p class="important">This one is not highlighted.</p>

SOMATECH IT – 0726 674 946 14


4. [attribute|="value"]: Selects elements with an attribute whose value is exactly the
specified value or starts with that value followed by a hyphen (-). This is commonly used
for selecting elements based on language codes or other prefixed attributes.

Syntax:

element[attribute|="value"] {
property: value;
}

Example:

a[lang|="en"] {
color: green;
}

Explanation: This will select any <a> element where the lang attribute value is "en" or
starts with "en-" (e.g., en-US, en-GB, etc.).

HTML example:

<a href="[Link] lang="en">English Link</a>


<a href="[Link] lang="en-GB">UK Link</a>
<a href="[Link] lang="fr">French Link</a>

5. [attribute^="value"]: Selects elements with an attribute whose value begins with the
specified value. This is useful for targeting elements with attributes that start with a
particular prefix.

Syntax:

element[attribute^="value"] {
property: value;
}

Example:

a[href^="[Link] {
font-weight: bold;
}

Explanation: This will apply a bold font weight to all <a> elements whose href attribute
value begins with "[Link] It can be used to target secure (HTTPS) links.

HTML example:

SOMATECH IT – 0726 674 946 15


<a href="[Link] Site</a>
<a href="[Link] Site</a>

6. [attribute$="value"]: Selects elements with an attribute whose value ends with the
specified value. This is particularly useful when working with file extensions or similar
patterns.

Syntax:

element[attribute$="value"] {
property: value;
}

Example:

img[src$=".jpg"] {
border: 2px solid black;
}

Explanation: This will apply a 2px black border to all <img> elements whose src
attribute ends with ".jpg".

HTML example:

<img src="[Link]" alt="Image 1">


<img src="[Link]" alt="Image 2">

7. *[attribute="value"]**: Selects elements with an attribute whose value contains the


specified value anywhere within it. This is useful for matching substrings within an
attribute.

Syntax:

element[attribute*="value"] {
property: value;
}

Example:

a[href*="example"] {
color: purple;
}

Explanation: This will select all <a> elements whose href attribute contains the
substring "example" anywhere in the URL.

SOMATECH IT – 0726 674 946 16


HTML example:

<a href="[Link] Link</a>


<a href="[Link] Link</a>

Combining Attribute Selectors

You can combine multiple attribute selectors to target more specific elements. You can even use
attribute selectors alongside other types of selectors like ID or class selectors.

Example:

input[type="text"][placeholder="Enter text"] {
background-color: lightblue;
}

Explanation: This will select <input> elements that have both a type="text" attribute and
a placeholder="Enter text" attribute, and it will apply a light blue background color to
them.

Summary of Attribute Selectors:

Selector Description Example


[attribute] Targets elements that a[href] { color: blue; }
have the specified
attribute, regardless of
its value.
[attribute="value"] Targets elements input[type="text"] {
where the attribute background: yellow; }
has a specific value.
[attribute~="value"] Targets elements with p[class~="highlight"] {
an attribute whose color: red; }
value contains a
specific word.
`[attribute ="value"]` Targets elements with an attribute
value that starts with a specified
value.
[attribute^="value"] Targets elements with a[href^="[Link] {
an attribute whose font-weight: bold; }
value starts with a
specified value.

SOMATECH IT – 0726 674 946 17


[attribute$="value"] Targets elements with img[src$=".jpg"] {
an attribute whose border: 2px solid black;
value ends with a }
specified value.
[attribute*="value"] Targets elements with a[href*="example"] {
an attribute whose color: purple; }
value contains a
specific substring.

Key Takeaways

• Attribute selectors are powerful tools for targeting elements based on the presence or
value of an attribute.
• You can use them to style elements dynamically, without relying on classes or IDs.
• Attribute selectors can be combined with other selectors for even more specific targeting.
• Modern web applications often use attribute selectors for styling form elements, links,
images, and other interactive components.

By understanding and utilizing attribute selectors, you can gain much more control over the styling
of your web pages and create more flexible and dynamic designs.

SOMATECH IT – 0726 674 946 18


CSS Properties: Grouped by Functionality

A. Text and Font Styling

CSS provides a wide variety of properties to style text and fonts on a webpage. These properties
control the appearance, size, color, and overall presentation of text elements. Below is a detailed
explanation of the most used CSS properties for text and font styling:

1. color

The color property in CSS is used to set the color of the text in an HTML element. You can use
predefined color names (like red, blue, etc.), hexadecimal values (like #FF5733), RGB values
(like rgb(255, 0, 0)), or HSL values (like hsl(0, 100%, 50%)).

Syntax:

p {
color: red; /* Predefined color name */
color: #FF5733; /* Hexadecimal color */
color: rgb(255, 0, 0); /* RGB color */
color: hsl(0, 100%, 50%); /* HSL color */
}

Example:

h1 {
color: blue; /* Sets the text color of h1 to blue */
}

2. font-family

The font-family property defines the typeface for text. You can specify a list of fonts, and if
the first choice is not available, the browser will try the next one in the list.

Syntax:

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

Here, if 'Arial' is not available, the browser will try 'Helvetica', and if that’s unavailable,
it will default to the generic sans-serif font family.

Example:

SOMATECH IT – 0726 674 946 19


h2 {
font-family: 'Georgia', serif;
}

3. font-size

The font-size property specifies the size of the font. It can be defined in various units, such as
pixels (px), ems (em), rems (rem), percentages (%), or points (pt).

Syntax:

p {
font-size: 16px; /* Pixel size */
font-size: 1em; /* Relative to the parent element's font size
*/
font-size: 1.5rem; /* Relative to the root element's font size
*/
}

Example:

h1 {
font-size: 32px; /* Sets the font size of h1 to 32 pixels */
}

4. font-style

The font-style property is used to set the style of the font. Common values include normal,
italic, and oblique. The italic value is typically used for emphasis, while oblique is
similar but has a slightly different slant.

Syntax:

p {
font-style: italic; /* Italic style */
font-style: oblique; /* Oblique style */
font-style: normal; /* Normal style */
}

Example:

em {
font-style: italic; /* Italicizes the text inside <em> */
}

SOMATECH IT – 0726 674 946 20


5. font-weight

The font-weight property controls the thickness of the font. Common values are normal,
bold, and lighter, or you can use numeric values between 100 and 900, where 400 is
equivalent to normal, and 700 is equivalent to bold.

Syntax:

p {
font-weight: bold; /* Bold text */
font-weight: 300; /* Lighter weight */
font-weight: 700; /* Bold weight */
}

Example:

strong {
font-weight: bold; /* Makes text inside <strong> bold */
}

6. text-align

The text-align property controls the horizontal alignment of text within an element. You can
align text to the left, right, center, or justify it across the width of its container.

Syntax:

p {
text-align: left; /* Aligns text to the left */
text-align: right; /* Aligns text to the right */
text-align: center; /* Centers the text */
text-align: justify; /* Justifies the text */
}

Example:

h1 {
text-align: center; /* Centers the text inside <h1> */
}

7. text-decoration

SOMATECH IT – 0726 674 946 21


The text-decoration property is used to apply decoration to text, such as underlining,
overlining, line-through (strikethrough), or none. This property also allows for other effects, such
as blink (though it's deprecated).

Syntax:

p {
text-decoration: underline; /* Underlines the text */
text-decoration: line-through; /* Strikes through the text */
text-decoration: none; /* Removes any text decoration */
}

Example:

a {
text-decoration: none; /* Removes underline from links */
}

8. line-height

The line-height property controls the amount of space between lines of text. It is commonly
used to improve the readability of text by increasing or decreasing the space between lines.

Syntax:

p {
line-height: 1.5; /* 1.5 times the font size */
line-height: 20px; /* Sets the line height to 20 pixels */
}

Example:

p {
line-height: 1.8; /* Sets the line height to 1.8 times the font
size */
}

9. letter-spacing

The letter-spacing property controls the amount of space between characters in a text
element. Positive values increase the spacing, while negative values decrease the spacing between
characters.

Syntax:

SOMATECH IT – 0726 674 946 22


p {
letter-spacing: 2px; /* Increases spacing between letters */
letter-spacing: -1px; /* Decreases spacing between letters */
}

Example:

h1 {
letter-spacing: 3px; /* Increases letter spacing in <h1> */
}

Summary of Text and Font Styling Properties

Property Description Common Values


color Sets the color of the text. Predefined colors, Hex,
RGB, HSL
font-family Specifies the font for the text. 'Arial', 'Helvetica', sans-
serif
font-size Controls the size of the font. px, em, rem, %, pt
font-style Sets the style of the font (italic, oblique, normal, italic, oblique
etc.).
font-weight Sets the thickness of the font. normal, bold, 100-900
text-align Aligns text horizontally within an element. left, right, center, justify
text- Adds decoration to text (underline, underline, line-through,
decoration strikethrough, etc.). none
line-height Controls the space between lines of text. Normal value, px, em,
percentage
letter- Adjusts the space between characters. px, em, rem, normal
spacing

These properties are essential for controlling the visual presentation of text in a webpage and can
be used individually or together to create a readable, visually appealing design. Mastery of these
properties will allow you to enhance the presentation of your text and make your website more
user-friendly and aesthetically pleasing.

B. Box Model

The CSS Box Model is one of the most fundamental concepts in web design. It dictates how
elements on a webpage are displayed, including their size, spacing, and how they interact with one
another. Understanding the box model is crucial for precise control over layout and design.

The box model consists of the following components:

• Content Box: The actual content of the box, such as text, images, or other elements.

SOMATECH IT – 0726 674 946 23


• Padding: The space between the content and the border. Padding is inside the element.
• Border: The line surrounding the padding (if defined). It separates the padding from the
margin.
• Margin: The outermost space that separates the element from others on the page. It is
outside the border.

Box Model Breakdown:

1. Content: The area where the actual content (like text or images) of the element is placed.
2. Padding: Space around the content. It creates inner space between the content and the
border.
3. Border: The border that surrounds the padding (and content).
4. Margin: Space outside the border, separating the element from others.

The total width and height of an element is the sum of the content's width/height, plus padding,
border, and margin (unless you use box-sizing: border-box).

1. width and height

The width and height properties define the dimensions of an element’s content box. They
specify how wide and tall the content area of the element is, and they can be set using various
units, such as pixels (px), percentages (%), ems (em), and rems (rem).

Syntax:

div {
width: 200px; /* Sets the width of the element to 200px */
height: 100px; /* Sets the height of the element to 100px */
}

Example:

[Link] {
width: 80%; /* Sets the width of the element to 80% of its
parent container */
height: 300px; /* Sets the height of the element to 300px */
}

2. padding

Padding is the space between the content and the border. It can be set uniformly on all sides or
individually for each side (top, right, bottom, left). Padding is part of the element's box, so
increasing padding increases the overall size of the element unless box-sizing: border-
box is used.

SOMATECH IT – 0726 674 946 24


Syntax:

div {
padding: 10px; /* Applies 10px padding on all sides */
padding: 10px 20px; /* Applies 10px padding on top and
bottom, 20px on left and right */
padding: 10px 20px 30px 40px; /* Applies top: 10px, right: 20px,
bottom: 30px, left: 40px */
}

Example:

[Link] {
padding: 15px; /* 15px padding on all sides */
}

3. border

The border property defines the boundary between the padding and the margin. A border can
have different styles (e.g., solid, dashed, dotted), widths (e.g., 1px, 3px), and colors (e.g.,
red, #000, rgba(0, 0, 0, 0.5)).

Syntax:

div {
border: 2px solid black; /* 2px wide solid black border */
border: 5px dashed blue; /* 5px wide dashed blue border */
border: 1px dotted red; /* 1px wide dotted red border */
}

Example:

[Link] {
border: 2px solid black; /* Creates a black border around the
div */
}

4. margin

The margin property controls the outermost space of an element, which separates it from
neighboring elements. It can be set individually for each side (top, right, bottom, left). Like
padding, margin also impacts the overall layout, but it is outside the element's box.

Syntax:

SOMATECH IT – 0726 674 946 25


div {
margin: 10px; /* 10px margin on all sides */
margin: 10px 20px; /* 10px top and bottom, 20px left and
right */
margin: 10px 20px 30px 40px; /* top: 10px, right: 20px, bottom:
30px, left: 40px */
}

Example:

[Link] {
margin: 20px; /* Adds 20px margin to all sides of the div */
}

5. box-sizing

The box-sizing property determines how the total width and height of an element are
calculated. By default, the width and height only apply to the content box. However, with box-
sizing: border-box, the padding and border are included in the element's total width and
height, making it easier to control the layout.

Syntax:

div {
box-sizing: content-box; /* Default behavior, only content box
is considered */
box-sizing: border-box; /* Includes padding and border in total
size */
}

Example:

css
CopyEdit
[Link] {
width: 200px;
height: 200px;
padding: 20px;
border: 5px solid black;
box-sizing: border-box; /* Ensures padding and border are
included in width and height */
}

Box Model Summary

SOMATECH IT – 0726 674 946 26


Component Description Impact on Layout
width & Define the size of the content Sets the main dimensions of the element.
height area.
padding Adds space between the Increases the total size of the element unless
content and the border. box-sizing: border-box is used.
border Specifies the border around Increases the total size unless box-sizing:
the padding. border-box is used.
margin Creates space outside the Does not affect the size of the element but
border between the element impacts positioning.
and other elements.
box- Determines how the width content-box: Excludes padding and
sizing and height are calculated. border from width/height. border-box:
Includes padding and border in width/height.

Practical Application

• The width and height properties are most often used to define the content box size.
• Padding is essential for creating inner space and giving elements breathing room,
especially in text-heavy elements.
• Borders are often used for visually separating elements, but it's important to be mindful of
how they affect layout if box-sizing is not set to border-box.
• Margins are useful for creating space between elements, allowing you to manage the
layout and positioning.
• The box-sizing property is particularly helpful in responsive design, where you want to
control the element’s total size more predictably.

By understanding and using these properties effectively, you can have fine-grained control over
the layout of your webpage, making it more organized and user-friendly.

C. Backgrounds

The background properties in CSS are used to control the background of an element. Backgrounds
can be set to solid colors, images, or gradients, and you can customize how the background behaves
in relation to the element it is applied to. The background properties are key to creating visually
appealing and user-friendly designs. They allow you to create a layered effect and control how the
background interacts with other content.

1. background-color

The background-color property is used to set the background color of an element. This can
be any valid color (like color names, hex values, RGB values, or RGBA for transparency). It helps
define the background's color for elements like divs, sections, or the entire page.

Syntax:

SOMATECH IT – 0726 674 946 27


element {
background-color: color;
}

Example:

div {
background-color: lightblue; /* Sets the background color to
light blue */
}

You can also use other values for background-color, such as #ff5733 (hex), rgb(255,
99, 71) (RGB), or rgba(255, 99, 71, 0.5) (RGBA with transparency).

2. background-image

The background-image property is used to set one or more background images for an element.
This property allows you to use images like JPEGs, PNGs, SVGs, or even gradients as
backgrounds.

Syntax:

element {
background-image: url('image_path');
}

Example:

div {
background-image: url('[Link] /*
Sets the background to an image */
}

You can also use multiple background images by separating the url() values with commas:

element {
background-image: url('[Link]'), url('[Link]');
}

3. background-position

The background-position property specifies the position of the background image within
an element. This property allows you to align the image to specific parts of the element (like the
top-left corner, center, bottom-right, etc.).

SOMATECH IT – 0726 674 946 28


The position is typically defined in terms of x (horizontal) and y (vertical) coordinates. You can
use values like pixels (px), percentages (%), or keywords (top, center, bottom, left,
right).

Syntax:

element {
background-position: x-position y-position;
}

Example:

div {
background-image: url('[Link]');
background-position: top left; /* Position the image at the top-
left corner */
}

You can also use pixel or percentage values to position the image more precisely:

div {
background-image: url('[Link]');
background-position: 50% 50%; /* Center the background image */
}

4. background-size

The background-size property is used to control the size of the background image. It defines
whether the background image should be scaled to fit or cover the element, or if you want to
specify exact dimensions for the image.

Values:

• auto: Keeps the image at its original size.


• cover: Scales the image to cover the entire element, potentially cropping it.
• contain: Scales the image to ensure it fits entirely within the element, while maintaining
its aspect ratio.
• You can also use specific values for width and height, such as 100% or 50px.

Syntax:

element {
background-size: size;
}

SOMATECH IT – 0726 674 946 29


Example:

div {
background-image: url('[Link]');
background-size: cover; /* Scales the image to cover the entire
element */
}

div {
background-image: url('[Link]');
background-size: 100% 100%; /* Stretches the image to fit the
full width and height of the element */
}

5. background-repeat

The background-repeat property specifies whether the background image should be


repeated. By default, the background image will repeat horizontally and vertically to fill the
element. This property allows you to control the repetition behavior.

Values:

• repeat: The image will repeat both horizontally and vertically.


• repeat-x: The image will repeat only horizontally.
• repeat-y: The image will repeat only vertically.
• no-repeat: The image will not repeat, and it will only display once.

Syntax:

element {
background-repeat: repeat;
}

Example:

div {
background-image: url('[Link]');
background-repeat: no-repeat; /* Ensures the image doesn't
repeat */
}

div {
background-image: url('[Link]');
background-repeat: repeat-x; /* Repeats the image horizontally
*/

SOMATECH IT – 0726 674 946 30


}

6. background-attachment

The background-attachment property controls whether the background image scrolls with
the page content or stays fixed in place.

Values:

• scroll: The background image scrolls with the content (default behavior).
• fixed: The background image stays fixed in place when the content scrolls.
• local: The background image scrolls with the element's content (useful for elements with
their own scrollbars).

Syntax:

element {
background-attachment: fixed;
}

Example:

div {
background-image: url('[Link]');
background-attachment: fixed; /* The background stays fixed when
scrolling */
}

Practical Application of Backgrounds

Here’s a summary of how the different background properties can be used in CSS:

• Use background-color to set a solid color as the background.


• Use background-image to set an image as the background.
• Use background-position to control where the background image is placed inside
the element.
• Use background-size to control the scaling of the background image (e.g., cover,
contain, or custom values).
• Use background-repeat to manage whether the background image repeats or not.
• Use background-attachment to control if the background image scrolls with the
content or stays fixed.

Example of a Full Background Layout:

SOMATECH IT – 0726 674 946 31


[Link] {
background-image: url('[Link]');
background-color: lightgrey;
background-position: center;
background-size: cover;
background-repeat: no-repeat;
background-attachment: fixed;
width: 100%;
height: 100vh; /* 100% of the viewport height */
}

Summary of Key Background Properties

Property Description Example Values


background- Sets the background #fff, lightblue, rgba(0, 0, 0,
color color. 0.5)
background- Sets a background image. url('[Link]'), linear-
image gradient(to right, red,
yellow)
background- Specifies the position of top left, center, 50% 50%
position the background image.
background- Specifies the size of the cover, contain, 100px 200px
size background image.
background- Defines the repetition repeat, no-repeat, repeat-x,
repeat behavior of the repeat-y
background.
background- Controls how the scroll, fixed, local
attachment background behaves
when scrolling.

Understanding how to use and combine these properties will allow you to create rich, visually
engaging backgrounds for your webpage elements.

D. Borders

Borders are essential in CSS for controlling the appearance of the edges of elements. They are
used to outline or separate content visually and can be styled with various properties. CSS provides
several options to customize borders, including their size, color, style, and rounding corners for a
more modern and clean design.

1. border-style, border-width, border-color

The border-style, border-width, and border-color properties are fundamental to


creating borders in CSS. These properties allow you to define the style, width, and color of the
border of an element. They can be set individually or as a shorthand using the border property.

SOMATECH IT – 0726 674 946 32


border-style

The border-style property specifies the style of the border. This property can accept one or
more of the following values:

• none: No border will be displayed (the default).


• solid: A solid, continuous border.
• dotted: A dotted border.
• dashed: A dashed border.
• double: A double-line border.
• groove: A 3D grooved border.
• ridge: A 3D ridged border.
• inset: A border that looks like the element is embedded within the page.
• outset: A border that looks like the element is raised above the page.

Syntax:

element {
border-style: solid;
}

Example:

div {
border-style: dashed; /* The border will be dashed */
}

border-width

The border-width property sets the width of the border. You can define the border width using
various units, such as px (pixels), em, rem, or pt (points). It can accept a single value (for all
sides), or multiple values (for different sides).

Syntax:

element {
border-width: 2px;
}

Example:

div {
border-width: 4px; /* The border will be 4 pixels thick */
}

SOMATECH IT – 0726 674 946 33


You can also specify different widths for each side:

div {
border-width: 1px 2px 3px 4px; /* Top, Right, Bottom, Left */
}

border-color

The border-color property sets the color of the border. It can accept any valid color value
such as color names, hexadecimal values, RGB, or RGBA values.

Syntax:

element {
border-color: red;
}

Example:

div {
border-color: #ff5733; /* The border color will be a shade of
red */
}

You can also specify different colors for each side:

div {
border-color: red green blue yellow; /* Top, Right, Bottom, Left
*/
}

Shorthand for Border

You can combine all three border properties (border-style, border-width, and border-
color) into one shorthand property called border.

Syntax:

element {
border: [border-width] [border-style] [border-color];
}

Example:

SOMATECH IT – 0726 674 946 34


div {
border: 2px solid #ff5733; /* A solid red border with 2px
thickness */
}

2. Rounded Borders: border-radius

The border-radius property is used to create rounded corners on elements. This property
allows you to give elements smooth curves rather than sharp angles, providing a modern look. You
can apply border-radius to all four corners of an element or specify different values for each
corner.

Syntax:

element {
border-radius: [radius];
}

Example:

div {
border-radius: 10px; /* This will round all four corners with a
10px radius */
}

Multiple Values for Border Radius

You can specify different values for each corner of the element using four values in the following
order: top-left, top-right, bottom-right, and bottom-left.

Syntax:

element {
border-radius: top-left top-right bottom-right bottom-left;
}

Example:

div {
border-radius: 10px 20px 30px 40px; /* Different radius for each
corner */
}

SOMATECH IT – 0726 674 946 35


Elliptical Borders

You can also create elliptical borders by specifying two values for each corner (horizontal radius
and vertical radius).

Syntax:

element {
border-radius: [horizontal-radius] [vertical-radius];
}

Example:

div {
border-radius: 15px 30px; /* Horizontal radius of 15px and
vertical radius of 30px */
}

Circular Borders

If the element has equal height and width, you can use the border-radius property to create
circular elements. This is particularly useful for profile pictures or buttons that should be circular.

Example:

div {
width: 100px;
height: 100px;
border-radius: 50%; /* 50% radius makes the element circular */
}

Practical Example of Borders and Border Radius

Here’s an example where we combine border-style, border-width, border-color,


and border-radius:

div {
width: 300px;
height: 200px;
border: 3px solid #4CAF50; /* A 3px solid green border */
border-radius: 15px; /* Rounded corners with a 15px radius */
padding: 20px;
margin: 20px;
background-color: #f2f2f2; /* Light background color */

SOMATECH IT – 0726 674 946 36


}

This will create a box with:

• A solid green border, 3px thick.


• Rounded corners with a 15px radius.
• Padding inside the box.
• Margin outside the box.
• A light gray background color.

Summary of Border Properties

Property Description Example Values


border- Specifies the style of the solid, dashed, dotted, double, groove,
style border. etc.
border- Specifies the width of 1px, 2em, 3rem, 4pt, etc.
width the border.
border- Specifies the color of the #ff5733, rgba(255, 99, 71, 0.5),
color border. red, rgb(255, 99, 71)
border- Rounds the corners of an 10px, 50%, 20px 30px 40px 50px, 50px
radius element. 30px, etc.

Practical Use of Borders:

• Use borders to separate content visually.


• Use border-radius for creating rounded elements like buttons or profile pictures.
• Combine border-style, border-width, and border-color for full border
control over elements.
• Create modern UI designs by combining different border styles with border-radius
for sleek, soft edges.

These border properties are commonly used for boxes, buttons, cards, images, and more, adding
polish and structure to your web design.

E. Lists and Tables

In CSS, both lists and tables play a significant role in organizing and presenting data or content in
a structured way. CSS allows us to customize lists and tables to achieve a more visually appealing
and efficient layout. The properties used for styling lists and tables are crucial for creating a clean
and well-organized design. Below are detailed explanations of the relevant properties for lists and
tables.

1. Lists

SOMATECH IT – 0726 674 946 37


Lists are used to present a collection of items in a specific order or unordered manner. In HTML,
there are three types of lists: ordered lists (<ol>), unordered lists (<ul>), and definition lists
(<dl>). CSS provides properties to customize the appearance of these lists.

list-style-type

The list-style-type property is used to define the type of marker (bullet or numbering)
used for list items. This property can be applied to both unordered and ordered lists.

Syntax:

ul {
list-style-type: [type];
}

Possible values for list-style-type include:

• disc: A filled circle (default for unordered lists).


• circle: An empty circle.
• square: A square bullet.
• decimal: A numbered list (default for ordered lists).
• lower-alpha: Lowercase letters (a, b, c, d...).
• upper-alpha: Uppercase letters (A, B, C, D...).
• lower-roman: Lowercase Roman numerals (i, ii, iii...).
• upper-roman: Uppercase Roman numerals (I, II, III...).
• none: No marker (used to hide the list markers).

Example:

ul {
list-style-type: square; /* List items will have square bullets
*/
}

ol {
list-style-type: upper-roman; /* List items will use uppercase
Roman numerals */
}

list-style-position

The list-style-position property determines where the list marker (bullet or number) will
appear in relation to the list items.

SOMATECH IT – 0726 674 946 38


Syntax:

ul {
list-style-position: [position];
}

Possible values for list-style-position:

• inside: The marker will be placed inside the list item box, so the marker will be indented
with the text.
• outside: The marker will be placed outside the list item box (default behavior).

Example:

ul {
list-style-position: inside; /* Marker will appear inside the
list item */
}

2. Tables

Tables are used for displaying tabular data, such as records, lists of items, and comparisons. CSS
provides several properties to control the appearance of tables, including how borders, spacing,
and layouts are handled.

border-collapse

The border-collapse property defines whether the borders between table cells should be
collapsed into a single border or remain separate.

Syntax:

table {
border-collapse: [value];
}

Possible values for border-collapse:

• collapse: Collapses the borders into a single border.


• separate: Keeps the borders of the table cells separate (default behavior).

SOMATECH IT – 0726 674 946 39


Example:

table {
border-collapse: collapse; /* Collapsing borders for a cleaner
look */
}

When border-collapse is set to collapse, the borders of adjacent cells are merged into a
single border, which gives the table a neat appearance. If set to separate, each cell’s borders
will remain independent of each other.

table-layout

The table-layout property defines the algorithm used to calculate the column widths and
overall layout of a table.

Syntax:

table {
table-layout: [value];
}

Possible values for table-layout:

• auto: The table layout is determined by the content of the table cells (default behavior).
The browser adjusts the table width based on the content inside each column.
• fixed: The table layout is fixed, and the column widths are determined by the width of
the table and the width of individual columns.

Example:

table {
table-layout: fixed; /* Table layout will be fixed */
}

When table-layout is set to fixed, the browser doesn’t take into account the content's width
to calculate the table layout. Instead, it uses the specified column widths (or default widths if none
are set).

Practical Examples

Lists Example
SOMATECH IT – 0726 674 946 40
ul {
list-style-type: circle;
list-style-position: inside;
}

ol {
list-style-type: lower-alpha;
list-style-position: outside;
}

This example will:

• Use a circular bullet for the unordered list (<ul>) with the bullet inside the text.
• Use lowercase alphabetical numbering for the ordered list (<ol>) with the numbering
outside the text.

Table Example

table {
width: 100%;
border-collapse: collapse; /* Collapse table borders */
table-layout: fixed; /* Fixed table layout */
}

th, td {
padding: 8px;
border: 1px solid #000;
}

th {
background-color: #f2f2f2;
text-align: left;
}

This example will:

• Create a table with collapsed borders and fixed layout.


• Add padding and a solid black border to both the table headers (<th>) and table data
(<td>).
• Set a light background color for the table headers and align the text to the left.

Complete List and Table Example:

<!DOCTYPE html>
<html lang="en">
<head>

SOMATECH IT – 0726 674 946 41


<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>List and Table Example</title>
<style>
ul {
list-style-type: square;
list-style-position: outside;
}

ol {
list-style-type: decimal;
list-style-position: inside;
}

table {
width: 100%;
border-collapse: collapse;
table-layout: fixed;
}

th, td {
padding: 10px;
border: 1px solid #ddd;
}

th {
background-color: #f4f4f4;
}
</style>
</head>
<body>
<h1>CSS Lists and Tables Example</h1>

<h2>Unordered List (Square)</h2>


<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>

<h2>Ordered List (Decimal)</h2>


<ol>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ol>

SOMATECH IT – 0726 674 946 42


<h2>Table</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>25</td>
<td>New York</td>
</tr>
<tr>
<td>Jane</td>
<td>30</td>
<td>Los Angeles</td>
</tr>
</tbody>
</table>
</body>
</html>

This page demonstrates the use of ordered and unordered lists with different list-style
properties and includes a simple table with fixed layout and collapsed borders.

Summary of List and Table Properties

Property Description Values Use Case


list- Defines the marker style disc, circle, Customize the appearance
style-type for list items square, of list markers (bullets or
decimal, etc. numbers)
list- Specifies the position of inside, Control whether the marker
style- the list marker outside is inside or outside the list
position item box
border- Determines whether collapse, Controls whether adjacent
collapse table borders are separate table cell borders merge
collapsed or separate into one or stay separate
table- Specifies how the table auto, fixed Control how the browser
layout layout is determined calculates table layout and
column widths

SOMATECH IT – 0726 674 946 43


By understanding and applying these properties, you can create well-structured, visually appealing
lists and tables on your website.

F. Positioning and Layout

In CSS, positioning and layout properties control the placement of elements within a webpage.
These properties enable you to create flexible and dynamic designs. You can position elements
relative to their parent containers, control the visibility of elements, and create responsive designs
using techniques such as flexbox and grid. Let’s dive into each of the key properties related
to positioning and layout.

1. position (static, relative, absolute, fixed, sticky)

The position property determines how an element is positioned within its container or relative
to other elements. It is essential for controlling how elements are laid out on the page.

Possible values of the position property:

• static: The default positioning for all elements. Elements are positioned based on the
normal document flow.

.element {
position: static; /* Default positioning */
}

• relative: The element is positioned relative to its normal position in the document flow.
You can adjust the element's position using top, right, bottom, and left properties,
but it will still occupy its original space in the document flow.

.element {
position: relative;
top: 10px; /* Moves the element 10px down from its original
position */
}

• absolute: The element is positioned relative to its nearest positioned ancestor (non-
static parent). If no such ancestor exists, it is positioned relative to the document body. It
is removed from the normal document flow, so it does not affect the layout of other
elements.

.element {
position: absolute;
top: 20px; /* Moves the element 20px from the top of its
parent */

SOMATECH IT – 0726 674 946 44


left: 30px; /* Moves the element 30px from the left of its
parent */
}

• fixed: The element is positioned relative to the viewport, so it stays fixed in place even
when the page is scrolled. It is removed from the normal document flow.

.element {
position: fixed;
top: 0; /* Fixed to the top of the viewport */
left: 0; /* Fixed to the left of the viewport */
}

• sticky: The element is positioned based on the user's scroll position. It acts like
relative until it reaches a defined scroll position, at which point it "sticks" to that
position.

.element {
position: sticky;
top: 10px; /* Stick the element 10px from the top of the
viewport when scrolling */
}

2. top, left, right, bottom

The top, left, right, and bottom properties define the position of an element when it has a
position value other than static.

• top: Sets the vertical position of the element from the top of its container.

.element {
position: absolute;
top: 50px; /* 50px from the top of the positioned ancestor
*/
}

• left: Sets the horizontal position of the element from the left of its container.

.element {
position: absolute;
left: 30px; /* 30px from the left of the positioned ancestor
*/
}

• right: Sets the horizontal position of the element from the right of its container.

SOMATECH IT – 0726 674 946 45


.element {
position: absolute;
right: 10px; /* 10px from the right of the positioned
ancestor */
}

• bottom: Sets the vertical position of the element from the bottom of its container.

.element {
position: absolute;
bottom: 0; /* 0px from the bottom of the positioned
ancestor */
}

3. z-index

The z-index property controls the stacking order of elements along the z-axis (front to back).
Elements with a higher z-index value will appear in front of those with a lower value. The z-
index only works on elements that have a position value other than static.

.element1 {
position: absolute;
z-index: 1; /* Element will be behind element2 */
}

.element2 {
position: absolute;
z-index: 2; /* Element will appear in front of element1 */
}

4. float

The float property is used to position an element to the left or right of its container, allowing
other elements to wrap around it. This property was traditionally used for layouts but is now less
common due to the use of newer layout methods like flexbox and grid.

Possible values for float:

• left: Floats the element to the left, allowing content to wrap around the right side.
• right: Floats the element to the right, allowing content to wrap around the left side.
• none: Removes the floating effect (default value).

SOMATECH IT – 0726 674 946 46


img {
float: left; /* The image will float to the left, and text will
wrap around it */
margin-right: 10px; /* Add space on the right side of the image
*/
}

5. clear

The clear property is used to control the behavior of elements after a floated element. It prevents
an element from being next to a floated element and can force the element to appear below the
float.

Possible values for clear:

• left: The element will be moved below any element that is floated to the left.
• right: The element will be moved below any element that is floated to the right.
• both: The element will be moved below any element that is floated, regardless of
direction.

.clear {
clear: both; /* Ensures the element is displayed below all
floated elements */
}

6. display (block, inline, inline-block, none, flex, grid)

The display property specifies the display behavior of an element, which is critical for layout
purposes. This property controls how elements interact with other elements in the document flow.

Possible values for display:

• block: Makes an element a block-level element. It starts on a new line, taking up the full
width available by default.

div {
display: block; /* The element will be a block-level element
*/
}

• inline: Makes an element an inline element. It does not start on a new line and only
takes up as much width as necessary.

SOMATECH IT – 0726 674 946 47


span {
display: inline; /* The element will be an inline element
*/
}

• inline-block: Combines the behavior of both inline and block elements. It allows the
element to be inline while maintaining block-level properties like width and height.

.element {
display: inline-block; /* The element behaves like an
inline element but supports block properties */
}

• none: Hides the element completely, removing it from the document flow.

.hidden {
display: none; /* The element will not be displayed */
}

• flex: The element becomes a flex container, allowing its children to be arranged using
flexbox.

.container {
display: flex; /* The container becomes a flex container */
}

• grid: The element becomes a grid container, allowing its children to be arranged using
CSS Grid.

.container {
display: grid; /* The container becomes a grid container */
}

7. overflow

The overflow property controls what happens when content overflows the bounds of an
element. It can be particularly useful for elements with a fixed size, such as containers or images.

Possible values for overflow:

• visible: Default value. The content is not clipped and will overflow the element if
necessary.
• hidden: The overflowed content will be clipped, and no scrollbars will appear.
• scroll: Scrollbars will appear if the content overflows, allowing users to scroll.
• auto: Scrollbars will appear only when necessary (i.e., when the content overflows).
SOMATECH IT – 0726 674 946 48
.container {
overflow: auto; /* Scrollbars will appear if content overflows
*/
}

Summary of Positioning and Layout Properties

Property Description Values Use Case


position Defines the positioning static, Used for controlling the
method for an element. relative, placement of elements
absolute, relative to their
fixed, sticky container or viewport.
top, left, Defines the position of the Any valid length or Used to position
right, element when position percentage. elements based on their
bottom is relative, container or viewport.
absolute, or fixed.
z-index Controls the stacking order Any integer value. Used to control which
of elements along the z- elements appear in front
axis. or behind others.
float Positions an element to the left, right, Used for image or text
left or right of its container, none wrapping, commonly
allowing text to wrap used in layouts.
around it.
clear Ensures that the element left, right, Used to manage layout
does not float next to both around floated elements.
another element.
display Specifies how an element is block, inline, Used for controlling the
displayed (block, inline, inline-block, layout behavior of
flex, grid, etc.). none, flex, grid elements.
overflow Controls the handling of visible, Used to manage content
content that overflows the hidden, scroll, that exceeds the bounds
element’s box. auto of its container.

By understanding and mastering these properties, you can create sophisticated and responsive
layouts, as well as control the positioning and visibility of elements in your designs.

G. Flexbox (Modern Layout Tool)

Flexbox, or the Flexible Box Layout, is a powerful tool in CSS that provides a more efficient way
to lay out, align, and distribute space among elements within a container, even when the size of
the items is unknown or dynamic. It is a more modern and flexible approach compared to
traditional layout techniques like floats or positioning. With Flexbox, creating complex layouts
becomes much simpler, as it provides more control over how elements are distributed and aligned
within a container.

SOMATECH IT – 0726 674 946 49


1. display: flex

The display: flex property defines a flex container, enabling the use of flexbox properties
on its child elements. The flex container’s children (known as flex items) will be laid out according
to the flexbox model.

• Syntax:

.container {
display: flex; /* Makes the container a flexbox container
*/
}

• Effect: When a container is set to display: flex, all of its immediate children become
flex items, and their layout behavior will follow the flexbox rules.

2. flex-direction

The flex-direction property defines the direction in which the flex items are placed within
the flex container. It sets the primary axis for the layout (horizontal or vertical).

• Possible values:
o row: (default value) The flex items are laid out in a horizontal row, from left to
right.
o row-reverse: The flex items are laid out in a horizontal row, from right to left.
o column: The flex items are laid out in a vertical column, from top to bottom.
o column-reverse: The flex items are laid out in a vertical column, from bottom
to top.
• Syntax:

.container {
display: flex;
flex-direction: row; /* Items are laid out horizontally */
}

• Effect: The flex-direction property determines the main axis, which controls the
direction in which flex items are aligned (either horizontally or vertically).

3. justify-content

The justify-content property is used to align the flex items along the main axis (horizontal
for row, vertical for column). It is useful for distributing space between items and aligning them
within the flex container.

SOMATECH IT – 0726 674 946 50


• Possible values:
o flex-start: Aligns items to the start of the container (default).
o flex-end: Aligns items to the end of the container.
o center: Aligns items in the center of the container.
o space-between: Distributes items with equal space between them, with no
space at the start or end.
o space-around: Distributes items with equal space around them, including space
at the start and end.
o space-evenly: Distributes items with equal space between and around them.
• Syntax:

.container {
display: flex;
justify-content: space-between; /* Items are spaced evenly,
with no space at the start and end */
}

• Effect: This property controls the distribution of items along the main axis, which is helpful
for creating layouts with evenly spaced or centered items.

4. align-items

The align-items property aligns the flex items along the cross axis (perpendicular to the main
axis). It is used to control the vertical alignment of items when the flex direction is row, and the
horizontal alignment when the flex direction is column.

• Possible values:
o flex-start: Aligns items to the start of the container (default).
o flex-end: Aligns items to the end of the container.
o center: Aligns items in the center of the container.
o baseline: Aligns items based on their baseline (useful for aligning text).
o stretch: Stretches the items to fill the container (default).
• Syntax:

.container {
display: flex;
align-items: center; /* Vertically aligns items to the
center of the container */
}

• Effect: This property allows you to control the alignment of items along the cross axis,
which is useful for vertically centering elements or aligning them at the top or bottom of
the container.

SOMATECH IT – 0726 674 946 51


5. flex-wrap

The flex-wrap property controls whether the flex items should wrap onto a new line or stay on
the same line if they do not fit within the container. By default, flex items try to fit into one line,
but this can be changed with flex-wrap.

• Possible values:
o nowrap: Default value. Flex items do not wrap, and overflow occurs if the items
exceed the container’s width.
o wrap: Flex items will wrap onto the next line if they do not fit within the container.
o wrap-reverse: Flex items will wrap onto the next line, but in reverse order.
• Syntax:

.container {
display: flex;
flex-wrap: wrap; /* Items will wrap to the next line if
needed */
}

• Effect: The flex-wrap property allows you to create responsive layouts where items
will wrap to the next line when the container is too small to hold them.

6. align-content

The align-content property is used to align the lines of flex items within a flex container
when there is extra space on the cross axis. It controls the distribution of space between multiple
lines of flex items (when wrapping occurs). This property only works if there are multiple rows of
flex items (i.e., when flex-wrap is set to wrap).

• Possible values:
o flex-start: Aligns the lines to the start of the container.
o flex-end: Aligns the lines to the end of the container.
o center: Aligns the lines in the center of the container.
o space-between: Distributes the lines with equal space between them.
o space-around: Distributes the lines with equal space around them.
o stretch: Stretches the lines to fill the container.
• Syntax:

.container {
display: flex;
flex-wrap: wrap; /* Enables wrapping of items */
align-content: space-between; /* Distributes space between
lines of items */
}

SOMATECH IT – 0726 674 946 52


• Effect: The align-content property is useful for aligning rows of items within a flex
container when the content is wrapped. It helps control the vertical space between the rows.

Summary of Flexbox Properties

Property Description Values Use Case


display: Defines the container flex Makes the container
flex as a flexbox, enabling a flex container.
its children to be flex
items.
flex- Defines the direction of row, row-reverse, Controls the main
direction the flex items (row or column, column- axis (horizontal or
column). reverse vertical).
justify- Aligns the items along flex-start, flex- Distributes space
content the main axis end, center, space- between items and
(horizontal or vertical). between, space- aligns them along the
around, space- main axis.
evenly
align- Aligns the items along flex-start, flex- Aligns items within
items the cross axis (vertical end, center, the container along
or horizontal). baseline, stretch the cross axis.
flex-wrap Controls whether the nowrap, wrap, wrap- Determines whether
flex items should wrap reverse items should wrap
onto a new line. when the container is
full.
align- Aligns multiple lines of flex-start, flex- Aligns rows of items
content flex items when there is end, center, space- when wrapping is
extra space on the cross between, space- enabled.
axis. around, stretch

By understanding and applying these Flexbox properties, you can create responsive layouts that
adjust to different screen sizes and automatically distribute space between elements in a consistent
and predictable way. Flexbox simplifies the process of aligning, distributing, and positioning
elements compared to older layout techniques like float and inline-block.

H. Grid (Advanced Layout)

CSS Grid Layout is a powerful tool that provides a two-dimensional layout system for web design.
Unlike Flexbox, which works along a single axis (either horizontally or vertically), CSS Grid
allows you to create complex layouts with both rows and columns. It offers more control over both
the placement of items and the overall layout of a container. With Grid, you can align and distribute

SOMATECH IT – 0726 674 946 53


items with more flexibility and precision, making it ideal for creating complex, responsive web
designs.

1. display: grid

The display: grid property is used to define an element as a grid container. It allows the
container’s child elements to become grid items that can be placed and aligned within a grid
structure.

• Syntax:

.container {
display: grid; /* Defines the element as a grid container
*/
}

• Effect: This property activates the grid layout for the container and its direct child
elements. Once applied, child elements will follow grid rules for positioning and alignment.

2. grid-template-columns

The grid-template-columns property defines the number of columns in a grid container


and their respective sizes. It specifies the width of each column, allowing you to create layouts
with fixed or flexible column widths.

• Syntax:

.container {
display: grid;
grid-template-columns: 100px 200px 300px; /* Three columns
with specific widths */
}

• Possible values:
o Fixed values: You can use pixels (px), percentages (%), or any other unit to set
specific column widths.
o Flexible values: The fr (fractional unit) represents a fraction of the available
space. For example, 1fr will take up one fraction of the remaining space in the
grid.

.container {
display: grid;

SOMATECH IT – 0726 674 946 54


grid-template-columns: 1fr 2fr 1fr; /* Creates three
columns, with the middle column taking twice the space of the
other two */
}

• Effect: The grid-template-columns property helps define the structure of the


grid’s columns. It determines how much space each column takes up and how the overall
grid layout will be divided.

3. grid-template-rows

The grid-template-rows property is similar to grid-template-columns but for rows.


It defines the number of rows in the grid container and their respective heights. You can set row
heights in fixed units, percentages, or flexible units.

• Syntax:

.container {
display: grid;
grid-template-rows: 150px 250px; /* Defines two rows with
fixed heights */
}

• Possible values:
o Fixed values: Use pixels (px), percentages (%), or other units.
o Flexible values: Use fr units to distribute space evenly or proportionally among
rows.

.container {
display: grid;
grid-template-rows: 1fr 2fr; /* Two rows with the second
row taking twice the space of the first */
}

• Effect: The grid-template-rows property sets the height of each row in the grid
container. This is useful when you need to control the vertical space allocation in the grid
layout.

4. grid-gap (or gap)

The grid-gap property (now simply called gap in modern CSS) defines the spacing between
the grid items, both horizontally (columns) and vertically (rows). It’s an efficient way to add space
between grid items without needing to adjust padding or margins.

SOMATECH IT – 0726 674 946 55


• Syntax:

.container {
display: grid;
grid-template-columns: 100px 100px 100px;
grid-template-rows: 100px 100px;
grid-gap: 10px; /* Adds a 10px gap between all rows and
columns */
}

• Possible values:
o gap: 10px;: A uniform 10px gap between rows and columns.
o gap: 10px 20px;: The first value sets the row gap (vertical space), and the
second sets the column gap (horizontal space).
• Effect: The grid-gap (or gap) property allows for efficient spacing between grid items.
It helps in controlling the spacing between items without adding individual margins or
padding to each grid item.

5. grid-area

The grid-area property allows you to define the position of grid items within the grid container.
You can specify which area of the grid the item should occupy, either by naming grid lines or by
defining specific grid rows and columns.

• Syntax (naming areas):

.container {
display: grid;
grid-template-columns: 100px 100px 100px;
grid-template-rows: 100px 100px;
grid-template-areas:
"header header header"
"main main sidebar"
"footer footer footer";
}

.header {
grid-area: header;
}
.main {
grid-area: main;
}
.sidebar {
grid-area: sidebar;
}
.footer {

SOMATECH IT – 0726 674 946 56


grid-area: footer;
}

• Syntax (explicit positioning):

.container {
display: grid;
grid-template-columns: 100px 200px 300px;
grid-template-rows: 100px 200px;
}

.item1 {
grid-area: 1 / 1 / 2 / 2; /* Starts at row 1, column 1 and
ends at row 2, column 2 */
}

.item2 {
grid-area: 2 / 2 / 3 / 4; /* Starts at row 2, column 2 and
ends at row 3, column 4 */
}

• Possible values:
o Named areas: You can assign names to areas in the grid using grid-
template-areas, which can then be referenced using grid-area.
o Explicit positioning: You can position an item using a four-value syntax: grid-
area: row-start / column-start / row-end / column-end.
• Effect: The grid-area property provides great flexibility in placing grid items into
specific parts of the grid. It allows for both intuitive placement using named areas and more
precise positioning using row and column numbers.

Summary of Grid Layout Properties

Property Description Values Use Case


display: Defines the container as grid Makes the container a
grid a grid, activating grid grid container.
layout rules.
grid- Defines the number and Pixels, percentages, Specifies the column
template- size of columns in the fr units, etc. layout for the grid.
columns grid.
grid- Defines the number and Pixels, percentages, Specifies the row
template- size of rows in the grid. fr units, etc. layout for the grid.
rows
gap Defines the spacing gap: 10px;, Adds uniform or
between grid items. gap: 10px custom space between
20px; rows and columns.

SOMATECH IT – 0726 674 946 57


grid-area Defines the position of a Named areas or Positions grid items in
grid item within the grid explicit row/column specific rows and
container. positions columns.

Summary of CSS Grid vs. Flexbox

Feature Flexbox Grid


Layout type 1D (one-dimensional) 2D (two-dimensional)
Flex direction Horizontal or vertical Rows and columns (both at the same time)
Best use case Aligning items in a single axis
Creating complex layouts with both rows
and columns
Item placement Items are aligned within a Items can be explicitly placed in grid cells
single axis
Control over Controls space between items in Controls both space between and
space one axis alignment in both axes

CSS Grid Layout provides a much more powerful and precise way to design web layouts compared
to Flexbox, especially for complex, multi-row and multi-column designs. While Flexbox is great
for simpler layouts, CSS Grid is ideal for more advanced and intricate grid-based designs.

4. Colors, Units, and Values in CSS

In this section, you’ll learn how to style your elements using color schemes and sizing units.
Understanding these is key to creating beautiful and responsive designs.

A. Colors in CSS

You can apply colors to text, backgrounds, borders, and more. There are several ways to define
color in CSS.

1. Color Names

These are predefined by CSS.

css
CopyEdit
h1 {
color: red;
background-color: yellow;
}

Examples: blue, green, orange, purple, teal, etc.

SOMATECH IT – 0726 674 946 58


2. Hexadecimal Values

A six-digit code that represents a color (#RRGGBB).

body {
background-color: #f2f2f2;
color: #333333;
}

• #000000 → Black
• #ffffff → White
• #ff0000 → Red

3. RGB (Red, Green, Blue)

Values between 0–255 for each color channel.

css
CopyEdit
p {
color: rgb(255, 0, 0); /* Red */
}

4. RGBA (RGB + Alpha)

Same as RGB, but with an added opacity channel.

div {
background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent black
*/
}

5. HSL & HSLA

• HSL = Hue, Saturation, Lightness


• HSLA = Adds Alpha (opacity)

button {
background-color: hsl(210, 100%, 50%);
}

B. Units in CSS

Used for spacing, sizing, positioning, etc.

SOMATECH IT – 0726 674 946 59


1. Absolute Units

Fixed size — doesn't change with screen size.

Unit Meaning
px Pixels
pt Points
cm Centimeters
in Inches

Example:

p {
font-size: 16px;
}

2. Relative Units

Scale based on parent elements or screen size — preferred in modern web design.

Unit Meaning
% Percentage of the parent
em Relative to the font-size of the parent
rem Relative to the root element (html)
vw Viewport width
vh Viewport height

Example:

.container {
width: 80%;
}

.title {
font-size: 2rem;
}

C. Common CSS Properties That Use Values

Property Example
color color: #333;
font-size font-size: 16px;
width, height width: 50%;

SOMATECH IT – 0726 674 946 60


margin, padding margin: 1em;
border border: 1px solid black;
opacity opacity: 0.7;
line-height line-height: 1.5;

Best Practice Tips

• Use relative units like rem, em, %, vw, and vh for responsive design.
• Use hex or HSL/HSLA for cleaner control over color design systems.
• Use variables (with modern CSS custom properties) to manage themes and consistency.

5. The CSS Box Model

Every HTML element on a webpage is treated as a box. The box model defines how these elements
occupy space and interact with each other.

Understanding the box model helps you control layout, spacing, and alignment with precision.

What Is the Box Model?

Every element is made up of four layers, from innermost to outermost:

+---------------------------+
| Margin |
| +---------------------+ |
| | Border | |
| | +---------------+ | |
| | | Padding | | |
| | | +-----------+ | | |
| | | | Content | | | |
| | | +-----------+ | | |
| | +---------------+ | |
| +---------------------+ |
+---------------------------+

SOMATECH IT – 0726 674 946 61


1. Content

This is where your text, image, or other data goes.

p {
width: 300px;
height: 200px;
}

2. Padding

The space between the content and the border. It creates inner spacing.

p {
padding: 20px;
}

You can also control individual sides:

padding-top: 10px;
padding-right: 15px;
padding-bottom: 10px;
padding-left: 15px;

Or shorthand:

padding: 10px 15px 10px 15px; /* top right bottom left */

3. Border

The line around the padding and content. You can style it:

p {
border: 2px solid black;
}

You can customize border width, style, and color:

border: 3px dashed red;

4. Margin

The space outside the border, used to create space between elements.

SOMATECH IT – 0726 674 946 62


p {
margin: 20px;
}

Like padding, you can target each side or use shorthand.

margin: 10px 0 30px 0; /* top, right, bottom, left */

Box Model in Action

.box {
width: 200px;
padding: 20px;
border: 2px solid #000;
margin: 30px;
}

• Total width = content + padding + border + margin


• In this example: 200px + 40px (left+right padding) + 4px (left+right border) + 60px
(left+right margin) = 304px width on the page

Best Practice Tips

• Use developer tools in your browser (like Chrome DevTools) to inspect box dimensions
visually.
• Consider using box-sizing: border-box; to make layout easier:

* {
box-sizing: border-box;
}

This tells the browser to include padding and border in the total width/height of an element.

6. Positioning and Layout in CSS

Positioning is how elements are placed on the page. This section is critical for creating
professional-looking layouts and responsive designs.

A. Static Position (Default)


SOMATECH IT – 0726 674 946 63
All elements are position: static; by default. They appear in the normal document flow.

div {
position: static;
}

You cannot use top, left, right, or bottom with static elements.

B. Relative Position

Moves an element relative to its normal position.

div {
position: relative;
top: 20px;
left: 30px;
}

The space where the element would normally be is still reserved.

C. Absolute Position

The element is removed from normal flow and positioned relative to the nearest positioned
ancestor (or the <html> if none found).

div {
position: absolute;
top: 10px;
right: 10px;
}

This is useful for precise layout, popups, tooltips, etc.

D. Fixed Position

The element is removed from flow and fixed to the viewport (browser window).

header {
position: fixed;
top: 0;
SOMATECH IT – 0726 674 946 64
width: 100%;
}

Great for sticky headers, navigation bars.

E. Sticky Position (Modern Layout)

The element toggles between relative and fixed based on scroll position.

nav {
position: sticky;
top: 0;
}

Use for sticky menus that scroll away only after a certain point.

F. Float

Float places elements to the left or right and lets text or elements wrap around them.

img {
float: left;
margin-right: 20px;
}

Use clear: both; to stop elements from wrapping.

G. Display Property

Defines the display behavior of an element.

Common values:

Value Purpose
block Element takes full width (e.g., <div>)
inline Sits next to other elements (e.g., <span>)
inline-block Like inline but supports width/height
none Hides the element
flex Enables flexbox layout (Part 7!)

SOMATECH IT – 0726 674 946 65


grid Enables CSS Grid layout

Example:

nav {
display: inline-block;
}

Best Practice Tips

• Use relative and absolute together for dropdowns, tooltips, etc.


• Use fixed for navigation and footers that stay visible.
• Use sticky for headers or sidebar menus.
• Master display, then proceed to flexbox and grid for modern responsive design.

7. CSS Flexbox (Flexible Box Layout)

Flexbox is a one-dimensional layout model used to arrange items in rows or columns, with
flexibility and alignment control.

Why Use Flexbox?

• Center items horizontally and vertically.


• Create responsive layouts.
• Control spacing between items.
• Reorder elements easily.

How It Works

Flexbox is applied to a container, and its children (items) respond accordingly.

<div class="container">
<div class="item">One</div>
<div class="item">Two</div>
<div class="item">Three</div>
</div>

.container {
display: flex;
SOMATECH IT – 0726 674 946 66
}

Main Flexbox Properties

1. display: flex;

Activates flexbox on the container.

.container {
display: flex;
}

2. flex-direction

Sets the main axis direction.

flex-direction: row; /* Default: left to right */


flex-direction: row-reverse;
flex-direction: column; /* Top to bottom */
flex-direction: column-reverse;

3. justify-content

Aligns items along the main axis.

justify-content: flex-start; /* Default: items start at left */


justify-content: flex-end; /* Items align at end */
justify-content: center; /* Center items */
justify-content: space-between;
justify-content: space-around;
justify-content: space-evenly;

4. align-items

Aligns items on the cross axis (vertical if row).

align-items: stretch; /* Default */


align-items: center;
align-items: flex-start;
align-items: flex-end;
align-items: baseline;

SOMATECH IT – 0726 674 946 67


5. flex-wrap

Allows items to wrap to the next line if needed.

flex-wrap: nowrap; /* Default */


flex-wrap: wrap;
flex-wrap: wrap-reverse;

6. gap

Adds spacing between flex items (modern & preferred way):

gap: 20px;

Child Item Properties

1. flex-grow

Allows items to grow relative to others.

.item {
flex-grow: 1;
}

2. flex-shrink

Controls how items shrink when space is tight.

.item {
flex-shrink: 1;
}

3. flex-basis

Initial size of the item before space is distributed.

.item {
flex-basis: 200px;
}

4. align-self

SOMATECH IT – 0726 674 946 68


Overrides align-items for an individual item.

.item {
align-self: flex-start;
}

Best Practice Tips

• Use flexbox for nav bars, card layouts, footers, headers.


• Combine flex with media queries for responsive design.
• Flexbox is for 1D layouts — use grid for 2D layouts (rows + columns).

Quick Example

.container {
display: flex;
justify-content: space-between;
align-items: center;
}

<div class="container">
<div>Home</div>
<div>About</div>
<div>Contact</div>
</div>

8. CSS Grid Layout

CSS Grid is a two-dimensional layout system, meaning it can control layout in rows and
columns at the same time. It’s perfect for full-page layouts, galleries, dashboards, etc.

Why Use CSS Grid?

• Structure whole web pages easily.


• Position items precisely in a grid.
• Create complex layouts without floats or positioning.
• Combine with Flexbox for ultimate layout control.

Basic Syntax

SOMATECH IT – 0726 674 946 69


.container {
display: grid;
grid-template-columns: 200px 1fr 200px;
grid-template-rows: auto 300px auto;
gap: 10px;
}

<div class="container">
<div>Header</div>
<div>Sidebar</div>
<div>Main Content</div>
<div>Footer</div>
</div>

Key Properties (for the Grid Container)

1. display: grid;

Activates Grid layout.

2. grid-template-columns / grid-template-rows

Defines number and size of columns/rows.

grid-template-columns: 1fr 1fr 1fr; /* 3 equal columns */


grid-template-rows: 100px auto 50px; /* fixed + dynamic height
rows */

Units:

• px, %, fr (fractional unit), auto

3. gap

Sets space between grid rows and columns.

gap: 20px; /* Row + column gap */


row-gap: 10px;
column-gap: 30px;

4. grid-template-areas

SOMATECH IT – 0726 674 946 70


Creates named layout regions for visual clarity.

.container {
display: grid;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
}

.header { grid-area: header; }


.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }

Key Properties (for Grid Items)

1. grid-column / grid-row

Specify where an item starts and ends.

.item1 {
grid-column: 1 / 3; /* spans from column 1 to 3 */
grid-row: 1 / 2;
}

2. grid-area

Assign an item to a named area from grid-template-areas.

.item1 {
grid-area: header;
}

3. place-items

Shorthand for aligning items inside their grid cell.

place-items: center;

Example: Simple Page Layout

SOMATECH IT – 0726 674 946 71


.container {
display: grid;
grid-template-areas:
"header header"
"menu content"
"footer footer";
grid-template-columns: 200px 1fr;
grid-template-rows: auto 1fr auto;
gap: 20px;
}

<div class="container">
<div class="header">Header</div>
<div class="menu">Sidebar</div>
<div class="content">Main Content</div>
<div class="footer">Footer</div>
</div>

Tips & Best Practices

• Use fr for flexible layouts (1fr 2fr etc.).


• Use auto when you don’t know the height/width.
• Combine Grid for page structure, Flexbox for inner alignment.
• Avoid mixing floats or inline-block with Grid.

Use Grid for:

• Full-page layouts
• Image galleries
• Admin dashboards
• Multi-column structures

9. CSS Media Queries & Responsive Design

Responsive Design ensures your website looks great on all devices — from phones to desktops.
CSS Media Queries allow us to apply different styles depending on the device's screen size or
features.

Why Use Media Queries?

SOMATECH IT – 0726 674 946 72


• Ensure usability on small screens.
• Avoid content overflow or zooming.
• Hide or rearrange content for mobile views.
• Create fluid, mobile-first experiences.

What Is a Media Query?

A media query checks for a condition (e.g., screen width) and applies styles only if that condition
is true.

Basic Syntax

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

Common Conditions You Can Test

Property Description
min-width Minimum width of the device/screen
max-width Maximum width of the device/screen
min-height Minimum height
orientation Portrait or landscape
resolution Screen resolution

Example: Basic Responsive Design

/* Base styles (default for larger screens) */


body {
font-size: 18px;
background-color: white;
}

/* Smaller devices (phones) */


@media (max-width: 600px) {
body {
font-size: 14px;
background-color: lightgray;
}

SOMATECH IT – 0726 674 946 73


}

Mobile-First Design

Best practice is to design for mobile devices first, then add styles for larger screens using min-
width.

/* Mobile styles */
.container {
flex-direction: column;
}

/* Tablet and up */
@media (min-width: 768px) {
.container {
flex-direction: row;
}
}

Common Breakpoints (Flexible, not fixed!)

Device Width Range


Mobile 0 – 600px
Tablet 600px – 1024px
Laptop 1024px – 1440px
Desktop 1440px and above

You can adjust breakpoints based on your design.

Media Query Examples

1. Change Layout on Small Screens

@media (max-width: 768px) {


.sidebar {
display: none;
}
}

2. Stack Columns Vertically on Phones

SOMATECH IT – 0726 674 946 74


.row {
display: flex;
}
.column {
flex: 1;
}

@media (max-width: 600px) {


.row {
flex-direction: column;
}
}

Responsive Images

Use the image to fit the screen:

img {
max-width: 100%;
height: auto;
}

Or hide large images on mobile:

@media (max-width: 500px) {


.large-banner {
display: none;
}
}

Best Practices

• Always test on real devices or emulators.


• Keep layouts fluid with % and fr, not px alone.
• Combine media queries with Flexbox or Grid for adaptive design.
• Avoid hiding too much content on mobile; prioritize instead.
• Try mobile-first first: write default styles for phones, override for desktops.

Sample Use Case: Responsive Navigation

SOMATECH IT – 0726 674 946 75


/* Desktop Nav */
.nav {
display: flex;
justify-content: space-between;
}

/* Mobile Nav */
@media (max-width: 600px) {
.nav {
flex-direction: column;
align-items: center;
}
}

10. CSS Transitions and Animations

CSS Transitions and Animations bring web pages to life by adding movement, smooth effects,
and interactivity without needing JavaScript. They're useful for hover effects, sliders, loaders, and
more.

Difference Between Transitions and Animations

Feature CSS Transitions CSS Animations


Triggered A change in state (like hover/focus) Runs automatically or when specified
by
Duration Controlled via transition- Controlled via animation-
duration duration
Keyframes Not used Uses @keyframes to define stages
Use Case Simple effects (hover/focus/click) Complex movement, looping effects

1. CSS Transitions

Basic Syntax

selector {
transition: property duration timing-function delay;
}

Example: Button Hover

SOMATECH IT – 0726 674 946 76


button {
background-color: blue;
color: white;
transition: background-color 0.3s ease;
}

button:hover {
background-color: green;
}

Common Transition Properties

• transition-property: The property to animate (color, transform, etc.)


• transition-duration: How long the animation takes (e.g., 0.5s)
• transition-timing-function: ease, linear, ease-in, ease-out,
cubic-bezier()
• transition-delay: Optional delay before transition starts

2. CSS Animations

Animations allow for more control, multiple keyframes, and can loop or auto-run.

Basic Syntax

css
CopyEdit
selector {
animation-name: slideIn;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-delay: 0.5s;
}

Define Keyframes

@keyframes slideIn {
from {
transform: translateX(-100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}

SOMATECH IT – 0726 674 946 77


Example: Animated Box

<div class="box"></div>
css
CopyEdit
.box {
width: 100px;
height: 100px;
background: red;
animation: bounce 1s infinite;
}

@keyframes bounce {
0% { transform: translateY(0); }
50% { transform: translateY(-50px); }
100% { transform: translateY(0); }
}

Animation Properties

Property Description
animation-name Name of the keyframes
animation-duration Total time of one animation cycle
animation-timing- How the animation progresses (ease, linear)
function
animation-delay Time before animation starts
animation-iteration- Number of times animation repeats (infinite or number)
count
animation-direction Normal, reverse, alternate
animation-fill-mode Controls how styles are applied before/after animation
(forwards, backwards)

Best Practices

• Use transitions for quick state changes (hover, focus).


• Use animations for storytelling, loaders, or effects that run independently.
• Avoid overusing animations – it can be distracting or reduce performance.
• Combine with transform and opacity for smooth effects (better performance).

Mini Project Ideas

SOMATECH IT – 0726 674 946 78


• Navigation menu that slides in using transform and transition.
• Image gallery where hovering shows image captions using opacity.
• Page loader using infinite keyframe animation with a spinner.

11. CSS Variables (Custom Properties)

CSS Variables — also called custom properties — let you define reusable values for colors,
spacing, fonts, and more. They improve maintainability, flexibility, and readability of your CSS
code — especially in large projects.

Why Use CSS Variables?

• Avoid repeating values (e.g., #1a1a1a multiple times).


• Easily update themes or color schemes.
• Create dark/light mode toggles.
• Centralize design tokens (spacing, font sizes, etc.).

Basic Syntax

Declare a Variable

You must declare variables inside a CSS selector — usually :root (global scope):

:root {
--primary-color: #3498db;
--font-size-lg: 18px;
--padding-base: 10px;
}

Use a Variable

To use a variable, wrap the name with var():

button {
background-color: var(--primary-color);
padding: var(--padding-base);
font-size: var(--font-size-lg);
}

SOMATECH IT – 0726 674 946 79


Scope of Variables

• Global: Declared in :root → available everywhere.


• Local: Declared inside a selector → available only inside that selector or its children.

:root {
--text-color: black;
}

.card {
--text-color: darkblue; /* overrides inside .card */
color: var(--text-color);
}

Example

:root {
--main-bg: #f0f0f0;
--highlight: gold;
--text-color: #333;
}

body {
background-color: var(--main-bg);
color: var(--text-color);
}

h1 {
background-color: var(--highlight);
}

If you later want to change --highlight to lightgreen, it updates everywhere it's used —
no need to hunt through all the rules!

Fallback Values

If the variable isn’t defined, CSS can fall back to a default value:

p {
color: var(--my-color, black); /* Use black if --my-color is
missing */}

Dynamic Usage with JavaScript

You can change variables with JavaScript at runtime:


SOMATECH IT – 0726 674 946 80
[Link]('--primary-color',
'crimson');

This is useful for toggling themes or user preferences dynamically.

Best Practices

• Use :root for global variables.


• Group variables by category (colors, spacing, typography).
• Use meaningful, scalable names (e.g., --primary-color, not --blue1).
• Combine with media queries for theme-based overrides.

Bonus: Theming Example (Light/Dark)

:root {
--bg-color: white;
--text-color: black;
}

.dark-mode {
--bg-color: #111;
--text-color: white;
}

body {
background: var(--bg-color);
color: var(--text-color);
}

Apply .dark-mode to the <body> or <html> element to switch themes.

12. CSS Flexbox (Flexible Box Layout)

Flexbox is a powerful layout tool in CSS that allows you to design flexible and responsive layouts
with ease. It provides a more efficient way to align and distribute space among elements in a
container, even when their size is unknown or dynamic.

Why Use Flexbox?

• Align elements both horizontally and vertically with minimal code.


• Create layouts that adjust automatically for different screen sizes (responsive design).
• Control the distribution of space and positioning of items without floats or positioning.
SOMATECH IT – 0726 674 946 81
Key Concepts of Flexbox

• Flex Container: The parent element that holds the flex items (direct children).
• Flex Items: The children inside the flex container that will be laid out in a flexible manner.

Basic Syntax

To activate flexbox, you need to apply display: flex (or display: inline-flex) to
the parent container.

.container {
display: flex;
}

Main Axis vs. Cross Axis

• Main Axis: The primary axis along which flex items are laid out (horizontal by default).
• Cross Axis: Perpendicular to the main axis (vertical by default).

Flexbox Properties for the Container

1. flex-direction

Defines the direction in which the flex items are placed.

• row (default): Items laid out horizontally, left to right.


• column: Items laid out vertically, top to bottom.
• row-reverse: Items laid out horizontally, right to left.
• column-reverse: Items laid out vertically, bottom to top.

.container {
display: flex;
flex-direction: row;
}

2. justify-content

Aligns the flex items along the main axis (horizontal by default).

• flex-start: Aligns items to the left (default).


• flex-end: Aligns items to the right.
• center: Centers items horizontally.
• space-between: Distributes items with equal spacing between them.

SOMATECH IT – 0726 674 946 82


• space-around: Distributes items with equal space around them.
• space-evenly: Distributes items with equal space between and around them.

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

3. align-items

Aligns the flex items along the cross axis (vertical by default).

• stretch (default): Items stretch to fill the container.


• flex-start: Aligns items at the top.
• flex-end: Aligns items at the bottom.
• center: Centers items vertically.
• baseline: Aligns items based on their text baseline.

.container {
display: flex;
align-items: center;
}

4. align-self

Allows individual flex items to override the align-items setting, providing control over
alignment on the cross axis for specific items.

.item {
align-self: flex-end;
}

Flexbox Properties for the Items

1. flex-grow

Defines how much a flex item should grow relative to the other items inside the flex container.
The default value is 0 (no growth).

.item {
flex-grow: 2; /* This item will take twice as much space as
others */
}

SOMATECH IT – 0726 674 946 83


2. flex-shrink

Defines how much a flex item should shrink relative to the other items when there is not enough
space. The default value is 1 (items shrink).

.item {
flex-shrink: 0; /* This item will not shrink */
}

3. flex-basis

Specifies the initial size of the item before any space distribution. The default is auto, meaning
the item will size itself based on its content.

.item {
flex-basis: 200px; /* Item will start with 200px width */
}

4. flex

A shorthand for flex-grow, flex-shrink, and flex-basis.

.item {
flex: 1 1 200px; /* Flex-grow = 1, flex-shrink = 1, flex-basis
= 200px */
}

Advanced Flexbox Properties

1. flex-wrap

By default, flex items are laid out in a single line. If the items overflow, you can use flex-wrap
to allow them to wrap into multiple lines.

• nowrap: Prevents wrapping (default).


• wrap: Allows wrapping into multiple lines.
• wrap-reverse: Allows wrapping but in reverse order.

.container {
display: flex;
flex-wrap: wrap;
}

2. gap
SOMATECH IT – 0726 674 946 84
The gap property defines the space between flex items. It’s a convenient shorthand for margin.

.container {
display: flex;
gap: 10px; /* Adds 10px space between each item */
}

Flexbox Layout Examples

1. Basic Layout with Flexbox

.container {
display: flex;
justify-content: space-between;
align-items: center;
}

.item {
width: 30%;
}

2. Creating a Responsive Grid with Flexbox

.container {
display: flex;
flex-wrap: wrap;
gap: 20px;
}

.item {
flex: 1 1 200px; /* Items take 200px, but can grow or shrink */
}

Best Practices with Flexbox

• Start with display: flex on the container.


• Use flex-direction: column or row depending on your layout needs.
• Use justify-content and align-items to position items efficiently.
• Use flex-wrap when you need the items to wrap on smaller screens.
• Avoid using fixed or absolute positioning with Flexbox when possible.

Mini Project: Flexbox Layout

SOMATECH IT – 0726 674 946 85


Create a simple, flexible grid layout for a photo gallery:

<div class="gallery">
<div class="photo"></div>
<div class="photo"></div>
<div class="photo"></div>
<div class="photo"></div>
<!-- More photos here -->
</div>

.gallery {
display: flex;
flex-wrap: wrap;
gap: 10px;
}

.photo {
background-color: #ddd;
height: 200px;
flex: 1 1 200px;
}

13. CSS Grid Layout

CSS Grid Layout is a powerful two-dimensional layout system that allows you to design complex
and responsive web layouts easily. Unlike Flexbox, which primarily deals with one-dimensional
layouts (either rows or columns), Grid allows you to handle both rows and columns at the same
time.

Why Use CSS Grid?

• Two-dimensional layout: Flexbox is excellent for one-dimensional layouts (row or


column), but Grid allows both rows and columns simultaneously.
• Precise control: Grid provides precise control over the placement of elements within a
container.
• Easier to create complex layouts: Designing complex structures like two-column layouts,
card layouts, and responsive grids becomes much easier with CSS Grid.

Basic Syntax

Define the Grid Container

SOMATECH IT – 0726 674 946 86


To create a grid layout, use display: grid on the container element.

.container {
display: grid;
}

Define the Rows and Columns

You define the grid's rows and columns using grid-template-rows and grid-
template-columns.

.container {
display: grid;
grid-template-columns: 200px 1fr 1fr; /* 3 columns: 200px, 1
fractional unit, 1 fractional unit */
grid-template-rows: auto; /* auto height for rows */
}

Grid Lines

• Grid lines refer to the lines that divide the grid container into rows and columns.
• Numbered lines: Grid lines are numbered, starting from 1 for both rows and columns.
• Negative numbers: You can use negative numbers to refer to grid lines counting from the
end of the container.

For example:

.container {
display: grid;
grid-template-columns: 100px 1fr 100px;
}

• Column lines are numbered as 1, 2, 3, with negative values counting from the right side
(-1, -2).

Grid Properties for the Container

1. grid-template-columns & grid-template-rows

Defines how many columns and rows you want in your grid container. You can use fixed sizes
(e.g., px, em), flexible units (fr), or percentage values.

• fr (fractional unit) is a flexible unit that takes up available space.

SOMATECH IT – 0726 674 946 87


.container {
display: grid;
grid-template-columns: 200px 1fr 1fr; /* 3 columns */
grid-template-rows: 100px auto; /* 2 rows */
}

2. grid-gap (or gap)

Defines the space between grid items. It can be applied to both rows and columns.

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

Grid Properties for Items

Once you’ve set the grid container, the next step is positioning items within the grid. You can use
grid-column and grid-row to control where an item is placed.

1. grid-column & grid-row

• grid-column: Defines the span of the item along the horizontal axis (columns).
• grid-row: Defines the span of the item along the vertical axis (rows).

Example: Placing an item that spans across multiple columns.

.item {
grid-column: 1 / 3; /* Span from column 1 to 3 */
grid-row: 1; /* Place in the first row */
}

You can also use the shorthand grid-area to define both grid-column and grid-row at
once.

2. grid-template-areas

The grid-template-areas property lets you name areas in the grid layout for a more
readable structure.

.container {
display: grid;
grid-template-columns: 1fr 2fr;

SOMATECH IT – 0726 674 946 88


grid-template-areas:
"header header"
"sidebar main";
}

.header {
grid-area: header;
}

.sidebar {
grid-area: sidebar;
}

.main {
grid-area: main;
}

This is useful when you want to clearly define the areas of your layout, like headers, footers,
sidebars, and main content.

Responsive Layouts with Grid

One of the key strengths of CSS Grid is its ability to adapt easily to various screen sizes. You can
use media queries to adjust the grid layout based on the screen size.

Example: A responsive 3-column layout that turns into 1 column on smaller screens.

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

@media (max-width: 768px) {


.container {
grid-template-columns: 1fr; /* 1 column on small screens */
}
}

Advanced Grid Features

1. minmax()

The minmax() function allows you to define a range of sizes for your grid columns or rows. This
ensures that elements don’t become too small or too large.

SOMATECH IT – 0726 674 946 89


.container {
display: grid;
grid-template-columns: repeat(3, minmax(100px, 1fr));
}

This example defines columns that are at least 100px wide but will grow to fill the available space.

2. auto-fill and auto-fit

The auto-fill and auto-fit keywords allow you to create flexible layouts where the grid
automatically adjusts the number of items based on available space.

• auto-fill: Fills the row with as many columns as possible.


• auto-fit: Similar to auto-fill, but it allows the grid to collapse columns if there are
fewer items than the available space.

.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}

Mini Project: Creating a Simple Grid Layout

Imagine you are designing a portfolio website, and you want to display a set of portfolio items in
a grid layout.

<div class="portfolio">
<div class="portfolio-item">Item 1</div>
<div class="portfolio-item">Item 2</div>
<div class="portfolio-item">Item 3</div>
<div class="portfolio-item">Item 4</div>
</div>

.portfolio {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 15px;
}

.portfolio-item {
background-color: #ddd;
height: 200px;
}

SOMATECH IT – 0726 674 946 90


The .portfolio container is a grid with three columns, and the .portfolio-item elements
are placed in the grid, with a gap between them.

Best Practices for CSS Grid

• Use grid-template-areas for better readability and maintenance of complex


layouts.
• Be mindful of accessibility — use appropriate HTML tags to define the structure (e.g.,
<header>, <footer>, <nav>, etc.).
• Start with a simple grid layout and add complexity as needed.
• Combine Grid with Flexbox for responsive designs.
• Use minmax() and auto-fill for fluid and flexible designs.

14. CSS Animation

CSS animations allow you to create dynamic visual effects without using JavaScript. You can
animate properties of elements, such as position, color, size, and more, using keyframes and
transitions. CSS animations are widely used to improve user experience by adding interactive and
attention-grabbing effects.

Why Use CSS Animation?

• Improved user experience: Animations can draw attention to important content or provide
feedback (e.g., highlighting a button when hovered).
• Smooth interactions: Animations allow you to create smooth transitions between states,
which can make the website feel more responsive and polished.
• No JavaScript required: Unlike JavaScript-based animations, CSS animations are
lightweight and do not require the use of additional libraries or scripts.

Basic Syntax for CSS Animation

@keyframes Rule

The @keyframes rule defines the animation by specifying the intermediate states (keyframes)
during the animation. Keyframes allow you to describe the progression of the animation at various
points (from 0% to 100% of the animation duration).

Example:

@keyframes exampleAnimation {
0% {
transform: rotate(0deg); /* Initial state */
}

SOMATECH IT – 0726 674 946 91


50% {
transform: rotate(180deg); /* Middle state */
}
100% {
transform: rotate(360deg); /* Final state */
}
}

Here, the animation rotates an element from 0 to 360 degrees.

animation Property

The animation property is shorthand for defining multiple aspects of the animation in one line,
including the name of the keyframes, duration, timing function, delay, iteration count, etc.

Example:

.element {
animation: exampleAnimation 2s ease-in-out infinite;
}

• exampleAnimation: The name of the keyframes to apply.


• 2s: Duration of the animation (2 seconds).
• ease-in-out: The timing function (the pace of the animation, easing in at the start and
easing out at the end).
• infinite: The number of iterations (infinite loop).

Key Properties for CSS Animations

• animation-name: Specifies the name of the @keyframes animation.


• animation-duration: Defines how long the animation should take to complete one
cycle.
• animation-timing-function: Describes how the animation will progress over
time (e.g., linear, ease, ease-in, ease-out, cubic-bezier()).
• animation-delay: Delays the start of the animation.
• animation-iteration-count: Specifies the number of times the animation should
run (can be infinite for continuous looping).
• animation-direction: Defines the direction of the animation (e.g., normal,
reverse, alternate).
• animation-fill-mode: Specifies how the animation should behave before or after
it’s executed (e.g., forwards, backwards, both).

Animation Timing Functions

SOMATECH IT – 0726 674 946 92


The animation-timing-function defines how the intermediate states of the animation are
calculated over the duration. Here are some common timing functions:

• linear: The animation progresses at a constant speed.


• ease: The animation starts slowly, speeds up, and then slows down again.
• ease-in: The animation starts slowly and then speeds up.
• ease-out: The animation starts quickly and then slows down.
• ease-in-out: The animation starts slowly, speeds up in the middle, and then slows
down again.
• cubic-bezier(): Allows you to define your own custom timing function using cubic
Bezier curves.

Example of a Basic Animation

Let's create a simple animation where a box moves across the screen.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<style>
@keyframes moveRight {
0% {
left: 0;
}
100% {
left: 500px;
}
}

.box {
width: 100px;
height: 100px;
background-color: blue;
position: relative;
animation: moveRight 2s ease-in-out infinite;
}
</style>
<title>CSS Animation Example</title>
</head>
<body>

<div class="box"></div>

SOMATECH IT – 0726 674 946 93


</body>
</html>

In this example, a .box element moves from left: 0 to left: 500px across the screen over
2 seconds.

Example of a Bounce Animation

You can also animate multiple properties simultaneously, such as moving and scaling an object.
Here's an example of a "bounce" effect:

@keyframes bounce {
0% {
transform: translateY(0);
}
50% {
transform: translateY(-30px);
}
100% {
transform: translateY(0);
}
}

.box {
width: 100px;
height: 100px;
background-color: red;
animation: bounce 1s ease-in-out infinite;
}

In this example, the .box element moves up and down (like a bounce) using translateY.

Chaining Multiple Animations

You can chain multiple animations by separating them with commas. For example, if you want an
element to rotate while also changing color:

@keyframes rotateAndColorChange {
0% {
transform: rotate(0deg);
background-color: blue;
}
100% {
transform: rotate(360deg);
background-color: red;
}

SOMATECH IT – 0726 674 946 94


}

.box {
width: 100px;
height: 100px;
animation: rotateAndColorChange 3s linear infinite;
}

Here, the .box will rotate 360 degrees while also changing color from blue to red over 3 seconds.

CSS Transitions vs. Animations

While both CSS Transitions and CSS Animations are used for adding motion and effects, they
serve different purposes:

• Transitions: Triggered by a change in state (e.g., hover, focus, or active states). They are
simpler to implement and are ideal for quick, one-time effects (e.g., button hover effect).
• Animations: More complex and allow for keyframes to define multiple intermediate steps.
Animations are best for continuous or multi-step effects.

Example of a Transition:

button {
background-color: blue;
transition: background-color 0.3s ease;
}

button:hover {
background-color: green;
}

In this case, the button changes color when hovered, and the color transition occurs smoothly over
0.3 seconds.

Example of an Animation:

@keyframes colorChange {
0% {
background-color: blue;
}
100% {
background-color: green;
}
}

button {

SOMATECH IT – 0726 674 946 95


animation: colorChange 2s infinite alternate;
}

In this case, the button continuously changes colors from blue to green.

Best Practices for CSS Animations

• Use animations sparingly: While animations can make a site look attractive, overuse can
be distracting. Only use animations when they serve a purpose (e.g., to highlight actions or
provide feedback).
• Ensure accessibility: Some users might be sensitive to motion. Consider using the
prefers-reduced-motion media query to reduce or disable animations for those
users.

Example:

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


.box {
animation: none;
}
}

Mini Project: Create a Bouncing Ball Animation

Create a page where a ball bounces across the screen. The ball should be green at the top of the
screen and turn blue when it reaches the bottom.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<style>
@keyframes bounce {
0% {
transform: translateY(0);
background-color: green;
}
50% {
transform: translateY(200px);
background-color: blue;
}
100% {
transform: translateY(0);

SOMATECH IT – 0726 674 946 96


background-color: green;
}
}

.ball {
width: 50px;
height: 50px;
background-color: green;
border-radius: 50%;
position: relative;
animation: bounce 2s ease-in-out infinite;
}
</style>
<title>Bouncing Ball Animation</title>
</head>
<body>

<div class="ball"></div>

</body>
</html>

Conclusion:

CSS Animations are a fantastic way to add dynamic effects to a webpage. By defining keyframes
and using the animation shorthand property, you can control the speed, direction, and timing of
visual effects. Additionally, CSS transitions and animations provide different ways to create
smooth interactions, each serving distinct use cases. By using these techniques, you can
significantly enhance user experience and make your website more engaging.

15. CSS Grid Layout

CSS Grid Layout is one of the most powerful layout systems in CSS. It provides a way to create
complex and flexible grid-based designs using a two-dimensional approach: rows and columns.
With Grid Layout, you can place elements anywhere within a grid, create layouts that adjust to
screen sizes, and control the spacing of items in a more efficient way than with traditional layout
techniques.

Why Use CSS Grid Layout?

• Two-dimensional layout control: Unlike Flexbox, which is one-dimensional (either a row


or a column), CSS Grid provides both row and column control simultaneously.

SOMATECH IT – 0726 674 946 97


• Simplified responsive design: CSS Grid makes it easier to design complex layouts that
adjust smoothly to different screen sizes.
• More control over spacing: CSS Grid allows precise control over the placement and
alignment of items, including gaps between them.

Basic Syntax for CSS Grid Layout

Defining a Grid Container

To create a grid, you need to first define a grid container using display: grid;. This container
will hold the grid items.

.container {
display: grid;
}

Grid Template Columns and Rows

You define the structure of your grid by specifying the number and size of columns and rows using
grid-template-columns and grid-template-rows. These properties control how
many columns and rows the grid should have, and how wide or tall each one should be.

Example:

.container {
display: grid;
grid-template-columns: 100px 200px 100px; /* Three columns */
grid-template-rows: 150px 200px; /* Two rows */
}

This will create a grid with 3 columns of varying widths (100px, 200px, and 100px) and 2 rows
with heights of 150px and 200px.

Placing Items on the Grid

Once you've defined the grid structure, you can place items within the grid using the grid item's
position. CSS Grid automatically places the items in the grid cells, but you can also explicitly
control the placement.

Grid Item Placement

You can place grid items in specific cells using the grid-column and grid-row properties.

Example:

SOMATECH IT – 0726 674 946 98


.item1 {
grid-column: 1 / 3; /* Spans from column 1 to column 3 */
grid-row: 1 / 2; /* Occupies the first row */
}

This will make .item1 span across columns 1 to 3 and occupy the first row.

Naming Lines and Areas

You can name the grid lines and then use those names to place items. This makes your code more
readable and flexible.

Example:

.container {
display: grid;
grid-template-columns: [start] 100px [line1] 200px [line2] 100px
[end];
grid-template-rows: 150px 200px;
}

.item1 {
grid-column: start / line2;
grid-row: 1;
}

Here, the grid lines are named, and the grid item is placed based on the names of those lines.

Grid Gap

The grid-gap property (or gap) controls the spacing between grid items, both horizontally and
vertically. It’s a shorthand for grid-column-gap and grid-row-gap.

Example:

.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 20px; /* Adds a 20px gap between grid items */
}

In this example, a 20px gap is added between each grid item, both vertically and horizontally.

Aligning and Justifying Grid Items

SOMATECH IT – 0726 674 946 99


CSS Grid allows for powerful alignment control using the align-items, justify-items,
align-self, and justify-self properties.

• align-items: Aligns grid items vertically within their grid cell.


• justify-items: Aligns grid items horizontally within their grid cell.
• align-self: Aligns an individual item vertically, overriding align-items.
• justify-self: Aligns an individual item horizontally, overriding justify-items.

Example of Aligning Grid Items

.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
align-items: center; /* Centers all grid items vertically */
justify-items: center; /* Centers all grid items horizontally
*/
}

This will center all grid items both vertically and horizontally within their grid cells.

Creating Responsive Grid Layouts

One of the key strengths of CSS Grid is its responsiveness. You can easily change the number of
columns, rows, or their size depending on the screen size using media queries.

Example:

.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
}

@media (max-width: 600px) {


.container {
grid-template-columns: repeat(1, 1fr); /* Switch to a single
column on smaller screens */
}
}

Here, the layout switches to a single column when the screen width is less than 600px, making the
design responsive.

Example of a Simple Grid Layout

SOMATECH IT – 0726 674 946 100


Here's an example of a basic grid layout with a header, sidebar, main content, and footer:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<style>
.container {
display: grid;
grid-template-columns: 200px 1fr; /* Sidebar and content */
grid-template-rows: 80px 1fr 50px; /* Header, content, and
footer */
grid-gap: 10px;
}

header {
grid-column: 1 / 3;
background-color: #f2f2f2;
padding: 20px;
text-align: center;
}

.sidebar {
background-color: #d3d3d3;
padding: 20px;
}

.main {
background-color: #ffffff;
padding: 20px;
}

footer {
grid-column: 1 / 3;
background-color: #f2f2f2;
padding: 10px;
text-align: center;
}
</style>
<title>CSS Grid Layout Example</title>
</head>
<body>

<div class="container">
<header>Header</header>

SOMATECH IT – 0726 674 946 101


<div class="sidebar">Sidebar</div>
<div class="main">Main Content</div>
<footer>Footer</footer>
</div>

</body>
</html>

In this layout:

• The header spans both columns.


• The sidebar occupies the first column.
• The main occupies the second column.
• The footer spans both columns at the bottom.

Grid Layout with Named Areas

You can name grid areas to make the code more readable and create a layout using those names.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<style>
.container {
display: grid;
grid-template-columns: 1fr 3fr;
grid-template-rows: 100px 1fr 50px;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
grid-gap: 10px;
}

header {
grid-area: header;
background-color: #f2f2f2;
padding: 20px;
}

.sidebar {

SOMATECH IT – 0726 674 946 102


grid-area: sidebar;
background-color: #d3d3d3;
padding: 20px;
}

.main {
grid-area: main;
background-color: #ffffff;
padding: 20px;
}

footer {
grid-area: footer;
background-color: #f2f2f2;
padding: 10px;
}
</style>
<title>Named Grid Layout</title>
</head>
<body>

<div class="container">
<header>Header</header>
<div class="sidebar">Sidebar</div>
<div class="main">Main Content</div>
<footer>Footer</footer>
</div>

</body>
</html>

In this example, the grid areas are named, and each element is placed into a named area (e.g.,
header, sidebar, main, footer). This method makes the CSS easier to read and manage.

Conclusion

CSS Grid Layout is a powerful tool for creating complex layouts with ease. It allows for two-
dimensional control over both rows and columns and provides flexibility when creating responsive
designs. The ability to define grid templates, place items precisely, and control spacing makes CSS
Grid an essential skill for any web developer looking to build modern and dynamic websites.

-END-
SOMATECH IT – 0726 674 946 103

You might also like