CSS Notes
CSS Notes
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>
p {
color: blue;
font-size: 20px;
}
Modern development uses CSS alongside frameworks like Flexbox, Grid, Bootstrap, Tailwind,
and preprocessors like SASS/SCSS, enabling faster and more maintainable styling.
CSS targets HTML elements using selectors, then applies rules (declarations) that define how
those elements should appear.
selector {
property: value;
}
Example:
h1 {
SOMATECH IT – 0726 674 946 2
color: green;
text-align: center;
}
Types of CSS
1. Inline CSS
CSS written directly within an HTML tag using the style attribute.
Good for testing, not recommended for production.
2. Internal CSS
<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>
"Cascading" means that the order of CSS rules matters. When multiple rules target the same
element:
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
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:
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:
<!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
Example:
<head>
<link rel="stylesheet" href="[Link]">
</head>
body {
background-color: #ffffff;
SOMATECH IT – 0726 674 946 5
font-family: 'Segoe UI', sans-serif;
}
h1 {
color: darkgreen;
}
Comparison Table
CSS selectors are used to target HTML elements that you want to style. The syntax consists of a
selector and declaration block.
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;
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
* {
color: red;
}
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
• 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:
Example:
div > p {
color: green;
}
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.
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:
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.
Syntax:
element::before {
content: "Text to appear before the element";
}
Example:
p::before {
content: "Note: ";
font-weight: bold;
}
HTML example:
<p>This is a paragraph.</p>
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
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.
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:
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:
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:
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:
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:
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:
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.
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.
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.
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:
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> */
}
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
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:
Example:
h1 {
letter-spacing: 3px; /* Increases letter spacing in <h1> */
}
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.
• Content Box: The actual content of the box, such as text, images, or other elements.
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).
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.
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:
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 */
}
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:
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.).
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:
Syntax:
element {
background-size: size;
}
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
Values:
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
*/
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 */
}
Here’s a summary of how the different background properties can be used in CSS:
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.
The border-style property specifies the style of the border. This property can accept one or
more of the following values:
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 */
}
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 */
}
div {
border-color: red green blue yellow; /* Top, Right, Bottom, Left
*/
}
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:
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 */
}
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 */
}
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 */
}
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 */
These border properties are commonly used for boxes, buttons, cards, images, and more, adding
polish and structure to your web design.
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
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];
}
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.
ul {
list-style-position: [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];
}
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];
}
• 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;
}
• 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;
}
<!DOCTYPE html>
<html lang="en">
<head>
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>
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.
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.
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.
• 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 */
• 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 */
}
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.
• 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.
• 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).
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.
• 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 */
}
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.
• 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.
• 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.
• 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
*/
}
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.
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.
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.
.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.
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 */
}
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.
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
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
• 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;
3. grid-template-rows
• 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.
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.
.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.
.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 {
.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.
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.
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
css
CopyEdit
h1 {
color: red;
background-color: yellow;
}
body {
background-color: #f2f2f2;
color: #333333;
}
• #000000 → Black
• #ffffff → White
• #ff0000 → Red
css
CopyEdit
p {
color: rgb(255, 0, 0); /* Red */
}
div {
background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent black
*/
}
button {
background-color: hsl(210, 100%, 50%);
}
B. Units in CSS
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;
}
Property Example
color color: #333;
font-size font-size: 16px;
width, height width: 50%;
• 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.
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.
+---------------------------+
| Margin |
| +---------------------+ |
| | Border | |
| | +---------------+ | |
| | | Padding | | |
| | | +-----------+ | | |
| | | | Content | | | |
| | | +-----------+ | | |
| | +---------------+ | |
| +---------------------+ |
+---------------------------+
p {
width: 300px;
height: 200px;
}
2. Padding
The space between the content and the border. It creates inner spacing.
p {
padding: 20px;
}
padding-top: 10px;
padding-right: 15px;
padding-bottom: 10px;
padding-left: 15px;
Or shorthand:
3. Border
The line around the padding and content. You can style it:
p {
border: 2px solid black;
}
4. Margin
The space outside the border, used to create space between elements.
.box {
width: 200px;
padding: 20px;
border: 2px solid #000;
margin: 30px;
}
• 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.
Positioning is how elements are placed on the page. This section is critical for creating
professional-looking layouts and responsive designs.
div {
position: static;
}
You cannot use top, left, right, or bottom with static elements.
B. Relative Position
div {
position: relative;
top: 20px;
left: 30px;
}
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;
}
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%;
}
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;
}
G. Display Property
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!)
Example:
nav {
display: inline-block;
}
Flexbox is a one-dimensional layout model used to arrange items in rows or columns, with
flexibility and alignment control.
How It Works
<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
}
1. display: flex;
.container {
display: flex;
}
2. flex-direction
3. justify-content
4. align-items
6. gap
gap: 20px;
1. flex-grow
.item {
flex-grow: 1;
}
2. flex-shrink
.item {
flex-shrink: 1;
}
3. flex-basis
.item {
flex-basis: 200px;
}
4. align-self
.item {
align-self: flex-start;
}
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>
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.
Basic Syntax
<div class="container">
<div>Header</div>
<div>Sidebar</div>
<div>Main Content</div>
<div>Footer</div>
</div>
1. display: grid;
2. grid-template-columns / grid-template-rows
Units:
3. gap
4. grid-template-areas
.container {
display: grid;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
}
1. grid-column / grid-row
.item1 {
grid-column: 1 / 3; /* spans from column 1 to 3 */
grid-row: 1 / 2;
}
2. grid-area
.item1 {
grid-area: header;
}
3. place-items
place-items: center;
<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>
• Full-page layouts
• Image galleries
• Admin dashboards
• Multi-column structures
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.
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 */
}
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
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;
}
}
Responsive Images
img {
max-width: 100%;
height: auto;
}
Best Practices
/* Mobile Nav */
@media (max-width: 600px) {
.nav {
flex-direction: column;
align-items: center;
}
}
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.
1. CSS Transitions
Basic Syntax
selector {
transition: property duration timing-function delay;
}
button:hover {
background-color: green;
}
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;
}
}
<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
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.
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
button {
background-color: var(--primary-color);
padding: var(--padding-base);
font-size: var(--font-size-lg);
}
: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 */}
Best Practices
:root {
--bg-color: white;
--text-color: black;
}
.dark-mode {
--bg-color: #111;
--text-color: white;
}
body {
background: var(--bg-color);
color: var(--text-color);
}
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.
• 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: The primary axis along which flex items are laid out (horizontal by default).
• Cross Axis: Perpendicular to the main axis (vertical by default).
1. flex-direction
.container {
display: flex;
flex-direction: row;
}
2. justify-content
Aligns the flex items along the main axis (horizontal by default).
.container {
display: flex;
justify-content: space-between;
}
3. align-items
Aligns the flex items along the cross axis (vertical by default).
.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;
}
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 */
}
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
.item {
flex: 1 1 200px; /* Flex-grow = 1, flex-shrink = 1, flex-basis
= 200px */
}
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.
.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 */
}
.container {
display: flex;
justify-content: space-between;
align-items: center;
}
.item {
width: 30%;
}
.container {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.item {
flex: 1 1 200px; /* Items take 200px, but can grow or shrink */
}
<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;
}
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.
Basic Syntax
.container {
display: grid;
}
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).
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.
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 */
}
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.
• 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).
.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;
.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.
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;
}
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.
This example defines columns that are at least 100px wide but will grow to fill the available space.
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.
.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}
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;
}
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.
• 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.
@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 */
}
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;
}
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>
In this example, a .box element moves from left: 0 to left: 500px across the screen over
2 seconds.
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.
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;
}
.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.
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 {
In this case, the button continuously changes colors from blue to green.
• 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:
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);
.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.
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.
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;
}
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.
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.
You can place grid items in specific cells using the grid-column and grid-row properties.
Example:
This will make .item1 span across columns 1 to 3 and occupy the first row.
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.
.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.
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);
}
Here, the layout switches to a single column when the screen width is less than 600px, making the
design responsive.
<!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>
</body>
</html>
In this layout:
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 {
.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