0% found this document useful (0 votes)
2 views20 pages

Return - Type Name : // Function Body

The document provides an overview of functions in C++, including their definition, calling, return types, parameters, and various concepts such as recursion, function overloading, and default arguments. It also explains the differences between call by value and call by reference, detailing when to use each method and their respective advantages and disadvantages. Additionally, it touches on library functions and the importance of the main function in C++ programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views20 pages

Return - Type Name : // Function Body

The document provides an overview of functions in C++, including their definition, calling, return types, parameters, and various concepts such as recursion, function overloading, and default arguments. It also explains the differences between call by value and call by reference, detailing when to use each method and their respective advantages and disadvantages. Additionally, it touches on library functions and the importance of the main function in C++ programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Functions in C++

A function is a building block of C++ programs that contains a set of statements which are
executed when the functions is called. It can take some input data, performs the given task,
and return some result. A function can be called from anywhere in the program and any
number of times increasing the modularity and reusability.
Function Definition
A function definition specifies the function name, what type of value it returns and what it
does. In C++, a function must be defined before it its used.
return_type name() {
// Function body
}
 return_type: Type of value the function returns.
 name: Name assigned to the function.
 Function body: Set of statements in curly brackets { } are executed when the function
is called.
Example:
// Defining function that prints hello
void printHello(){
cout << "Hello Geeks";
}
The above function is named printHello. Only the single statement that prints “Hello
Geeks” is the part of function body. The return type of the function is void, which is used
when function does not return anything.
Function Call
Once the function is defined, we can use it anywhere in the program simply by calling it
using its name with () parenthesis.
Example:
{...}
// Calling function fun
printHello();

{...}

Output
Hello Geeks
The function printHello is called using its name in the main along with parenthesis. When
called, printHello’s body is executed and the text “Hello Geeks” is printed.
Return Type
We have seen an example of function that does not return anything. But functions can
return some value as a result of its execution. The type of this value should be defined as
the return_type of the function.
Example:
{...}
// Defining function that returns 10
int getTen(){
int res = 10
return res;
}

int main() {

// Calling function getTen()


cout << getTen();

{...}

Output
10
In this example, the getTen() function is supposed to return the integer value. So, the return
type of the function is specified as int. Then the return keyword is used to return the
variable res from the function to the point where it is called. The call of the function is
replaced by the value it returns, so res, whose value is 10 is printed.
Note: Only one value can be returned from the function, and it must be of the same type as
of function’s return type.

Parameters or Arguments
A function can also take some input data to process. These values are called function
arguments and are supplied to the function at the function call. To receive these values, we
define placeholder variables called parameter inside parenthesis in function definition. They
should be specified with their types and names.
return_type name(type1 name1, type2 name2...) {
// Function body
return val;
}
name1, name2 and so on are the parameter names using which they will be accessed in
the function.
Example:
{...}
// Defining function that prints given number
void printNum(int n){
cout << n << endl;
}

int main() {
int num1 = 10;
int num2 = 99;

// Calling printNum and passing both


// num1 and num2 to it one by one
printNum(num1);

{...}

Output
10
99
In the above program, printNum() function is defined with one integer parameter n that it
prints. It means that it will take one value of integer type while calling and print it. We
called printNum() two times, one with num1 and one with num2, and in each call, it prints
the given number. Note that we refer to the passed argument using the
name n not num1 or num2 in the function. It is due to the concept called scope of
variables in the main and printNum() function.
Here, there can be one question. Why didn’t we call the function with both numbers at
once? The answer lies in the printNum() definition. We have defined the function that only
takes one value of integer type as parameter, so we cannot pass two values. In other
words,
A function can only take as many arguments as specified in the function definition
and it is compulsory to pass them while calling it. Also, they should be of same type
as in the function definition.

There are also other different ways to pass arguments to the function in C++. Refer to this
article to know more – Parameter Passing Techniques in C++
Forward Declaration
In C++, a function must be defined before its call. Otherwise, compiler will throw an error.
To resolve this, we can just declare the function before the call and definition to inform the
compiler about function’s name and return type. This is called forward declaration or
just function declarations.
return_type name();
Above is the function declaration that tells the compiler that there is a function with the given
name and return type in the program. Writing parameter in the function declaration is
optional but valid.
return_type name(type1, type2 ...);
The above variation of the function declaration is also called function
prototype or function signature. If this declaration is present before the function call, then
we have the freedom to define the function anywhere in the program.
Note: Function declarations are compulsory, but the function definition already contains the
function declaration as a part of it, so it is not explicitly needed when function is defined at
the start.

Library Functions
Until now, we have discussed function which we define by ourselves. These functions are
called user defined functions for obvious reasons.
C++ also provides some in-build functions that are already defined inside different libraries
to simplify some commonly performed tasks. These functions are Library Functions which
can be directly called to perform the task.
Example:
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
int n = 3;
int m = 6;

// Call library function max() that


// returns maximum value between two
// numbers
cout << max(3, 6);

{...}

Output
6
The max() function in the above code returns the larger value among two values passed as
argument. It is defined in the algorithm library, so we had to include the relevant header
file <algorithm> to use it.
Similarly, C++ provides a lot of in-built functions to make our life easier. It is preferred to use
in-built functions wherever we can.
Default Arguments
Earlier, we said that it is compulsory to pass all the arguments in the function call. But C++
also provides a work around for this. For each function argument, a default value can be
defined that will be used when no value is passed for that argument in the function call.
These are called default arguments in C++.
Main Function
As you may have noticed from the above program, main is also the function. In C++,
the main function is a special function that every C++ program must contain. It serves as
the entry point for the program. The computer will start running the code from the beginning
of the main function. The return value of the main function indicates the successful or
unsuccessful execution of the program.
Recursion
When function is called within the same function, it is known as recursion. The function
which calls itself is known as recursive function and such calls are called recursive calls.
Recursion is an important concept in programming that simplifies a lot of problems are
complex to handle using normal programming means.
Function Overloading
Up until now, we know that an identifier can only be used only once in the program. The
name of the function is also an identifier, so it should be unique as well.
Image a scenario where you have a function that performs the multiplication of two integers,
but you also need to a function that multiplies two integers that are in the form of strings.
Normally, you may have to use two functions with different names for this purpose. In large
codebase, there can be many such cases and creating and remembering the names of
these functions can be hectic.
This problem can be solved though function overloading. Function overloading refers to
the feature in C++ where two or more functions can have the same name but different
parameters. It allows us to use the same function name for different arguments but same
purpose. This helps in clean semantically understandable code.

Call by Value and Call by Reference in C++:


If you're new to coding, you might have not heard of Call by Value and Call by
Reference in C++ programming language. In this blog post of C++ tutorial, we're going
to take a look at the basics of both concepts in C++. You can also explore C++ Online
Course Free so that even novice coders can better understand them. We'll also discuss
when it's best to use one or the other while writing the code in C++, ensuring that your
program runs efficiently and correctly.
Ways of Passing Data to a Function
We have already seen functions and their various aspects like formal
parameters and actual parameters in the section, Functions in C++. In
the function call, we used to pass parameters/arguments/data to the
function that is being called.
There are two ways to pass the data to a function in the C++ language:
1. call by value
2. call by reference
Call by Value in C++
In this method, the value of the actual parameteris passed to the
corresponding formal parameter of the called function. This technique ensures that
the original data i.e. actual parameter does not get altered by the called function,
as the called function deals only with a copy of that data.
When a programmer opts for the call by value, the memory space for the formal
parameters is allocated separately in the function stack, which further reinforces
the fact that the original data remains untouched. Thus, formal
parameters and actual parameters are allocated to different memory locations.

When to use Call by Value in C++

 When you do not want to change the actual parameters of the function.
 When you want to make copies of the data instead of the actual data.
 When space is not an issue.
 Usually, when you do not deal with recursion or backtracking.

Call by Value in C++ With Example

#include <iostream>
using namespace std;
void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
int main() {
int a = 40;
int b = 50;
cout << "Before swap: a = " << a << " b = " << b << endl;
swap(a, b);
cout << "After swap: a = " << a << " b = " << b << endl;
return 0;
}
The above program in C++ Compiler swaps the values of the variables, a and b. In
the main() function, the function call passes the actual parameter values i.e.
values of a and b to the swap() function. The swap() function swaps the values
of a and b.
Due to the call by value method, the value of the original
variables a and b remains unchanged even after swapping by the swap() function.
Output Before swap: a = 40 b = 50 After swap: a = 40 b = 50

Advantages of Using Call by Value in C++

 This method does not change the original variable. In other words, it is
preserving data.
 Whenever a function is called, it does not ever impact the actual contents of the
actual arguments.
 Here, the value of actual arguments passes to the formal arguments. Therefore,
any changes made in the formal argument do not impact the real cases.

Disadvantages of Using Call by Value in C++

 Data passed is stored in temporary memory.


 You can’t operate over the actual data but rather on a temporary copy of the
data, because of which changes made in the data in the function are not
reflected in the main() function.
 Memory space required while using string, array, vector, etc can be huge.
 Solving backtracking and recursion can be complex using call-by-value.

Call by Reference in C++


In this method, instead of passing the values of the actual parameters to the formal
ones, the addresses of the actual parameters are passed. Therefore, the
modification by the called function to the formal parameters affects the actual
parameters as well.

When a programmer opts for the call by reference, the memory space for
the formal parameters and the actual parameters are the same. All the
operations in the function are performed on the value stored at the address of
the actual parameters, and the modified value gets stored at the same address.

This technique not only conserves memory but also simplifies collaboration, as
complex data types like arrays or structures can easily be manipulated without
being duplicated needlessly.

When to use Call by Reference in C++

 When the programmer wants to modify the original value of a variable within a
function and have those modifications reflected in the calling code.
 Suppose, you have a large object (e.g., a complex data structure or a class
instance) and you want to avoid the overhead of copying it.
 When you need to modify the function parameters themselves, rather than just
the values they represent.
 when working with large data, since passing by reference does not create a copy
of the data. It increases efficiency.
Call by Reference in C++ Compiler With Example

#include <iostream>
using namespace std;
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5;
int y = 10;
cout << "Before swap: x = " << x << " , y = " << y << endl;
swap(&x, &y);
cout << "After swap: x = " << x << ", y = " << y << endl;
return 0;
}
In the above program of swapping two numbers, the main()function passes
the address of the two variables, a and b as actual parameters in the function
call denoted by the reference operator &.
The swap() function uses the pointer to get the value of the variables whose
addresses are passed by the function call. After swapping the values, the value of
the actual parameters gets permanently modified as the address of the variables
is passed.

Output

Before swap: x = 5, y = 10 After swap: x = 10, y = 5

Advantages of Using Call by Reference in C++

 The function can change the value of the argument. Thus, it is very beneficial.
 It does not create duplicate data for holding values which helps in saving the
memory space.
 It helps in avoiding changes that occur by mistake.
 A person who reads the code is not aware that the value can be modified in the
function.

Disadvantages of Using Call by Reference in C++

 A function taking in a reference requires ensuring that the input is non-null. Thus,
a null check is not supposed to be made. Thus, it has a non-null guarantee.
 Passing by reference makes the function not pure theoretically
 With references, a lifetime guarantee is a big problem. It is particularly dangerous
when working with lambdas and multi-threaded programs.

Difference between Call by Value and Call by Reference in C++


Aspect Call by Value Call by Reference
What is passed Copies the actual value of the Passes a reference or memory address
argument. of the argument.
Changes made to the parameter inside Changes made to the parameter inside
Modification of
the function do not affect the original the function directly affect the original
argument
argument. argument.
Typically consumes less memory as it
May consume more memory as it uses
Memory Usage creates a separate copy of the
references to the original data.
argument.
Generally faster due to the smaller data May be slower due to the need to
Performance
transfer. access data through references.
Data Type Suitable for simple data types (int, float, Suitable for complex data types (arrays,
Constraints etc.). objects, etc.).
Risk of
Reduces the risk of unintentional side Increases the risk of unintentional side
unintended
effects. effects.
changes

Summary

call by value and call by reference in C++ are important concept to


understand if you want a deeper conceptual understanding of computer
programming. call by value copies a variable's value whereas call by
reference passes a pointer instead. Depending on what the output is supposed to
be, developers need to decide which one they should use.
Consider enhancing your knowledge and gaining recognition by enrolling in C++
Certification Training, which will provide comprehensive guidance and hands-on
experience in mastering various concepts and techniques in C++ programming.
CSS (Cascading Style Sheets) is a language designed to simplify the process of making web pages
presentable.
 It allows you to apply styles to HTML documents by prescribing colors, fonts, spacing, and
positioning.
 The main advantages are the separation of content (in HTML) and styling (in CSS) and the same
CSS rules can be used across all pages and not have to be rewritten.
 HTML uses tags and CSS uses rule sets.
 CSS styles are applied to the HTML element using selectors.
Why CSS?
 Saves Time: Write CSS once and reuse it across multiple HTML pages.
 Easy Maintenance: Change the style globally with a single modification.
 Search Engine Friendly: Clean coding technique that improves readability for search engines.
 Superior Styles: Offers a wider array of attributes compared to HTML.
 Offline Browsing: CSS can store web applications locally using offline cache, allowing offline
viewing.
CSS Syntax
CSS consists of style rules that are interpreted by the browser and applied to the corresponding
elements. A style rule set includes a selector and a declaration block.
 Selector: Targets specific HTML elements to apply styles.
 Declaration: Combination of a property and its corresponding value.
// HTML Element
<h1>GeeksforGeeks</h1>
// CSS Style
h1 { color: blue; font-size: 12px; } Where - Selector - h1
Declaration - { color: blue; font-size: 12px; }
 The selector points to the HTML element that you want to style.
 The declaration block contains one or more declarations separated by semicolons.
 Each declaration includes a CSS property name and a value, separated by a colon.
Example
p{
color: blue;
text-align: center;
}
CSS declaration always ends with a semicolon, and declaration blocks are surrounded by curly braces.
In this example, all paragraph element (<p> tag) will be centre-aligned, with a blue text color.
CSS Features and Use Cases
1. Changing Text Color : Changes the text color of all <p> elements to green.
<html> <head>
<style>
p{
color: green;
}
</style>
</head>
<body> <p>This text is green.</p> </body>
</html>
2. Cascading in CSS : CSS resolves conflicts by prioritizing rules based on specificity and order. Shows
how CSS applies rules based on specificity.
<html> <head>
<style>
*{ color: black; }
p{ color: blue; }
#special { color: orange; }
</style> </head>
<body>
<p>This text is blue.</p>
<p id="special">This text is orange.</p>
</body> </html>
3. Background Color: Sets the background color of a <div> to chocolate.
<html> <head>
<style>
div { background-color: chocolate; width: 100px; height: 100px; }
</style>
</head>
<body>
<div>Hello GFG</div>
</body> </html>
4. Centering Text: Centers text horizontally within a container.
<html> <head>
<style>
.center-text { text-align: center; }
</style>
</head> <body>
<div class="center-text">Hello, World!</div>
</body> </html>
5. Adding Padding: Adds padding around the content inside a <div>.
<html> <head>
<style>
div { padding: 20px; border: 1px solid black; }
</style>
</head> <body>
<div>Hello with padding</div>
</body> </html>
6. Hover Effects : Changes button color on hover for interactive effects.
<html> <head>
<style>
button { background-color: greenyellow; color: white;
padding: 10px 20px; border: none; border-radius: 5px;
transition: background-color 0.3s ease;
}
button: hover { background-color: blue; }
</style>
</head> <body>
<button>Hover me</button>
</body> </html>
7. Font Weight: Makes text bold using the font-weight property.
<html> <head>
<style>
p{ font-weight: bold; }
</style>
</head> <body>
<p>This is bold text.</p>
</body> </html>
8. Flexbox for Centering Items Centers an item within a container using Flexbox.
<html> <head>
<style>
body { margin: 0; display: flex; justify-content: center; align-items: center;
height: 100vh; background: #f4f4f4; }
.container { display: flex; justify-content: center;
align-items: center; width: 300px;
height: 200px; background: #4caf50; color: white; }
</style>
</head> <body>
<div class="container">Centered</div>
</body>
</html>
9. Font Size: Sets the font size of text to 24 pixels.
<html> <head>
<style>
p{ font-size: 24px; }
</style>
</head> <body>
<p>Large text</p>
</body>
</html>
Key Advantages and Disadvantages of CSS
Advantages of CSS
 Simplifies web design and maintenance.
 Enhances website performance and user experience.
 Supports responsive and adaptive designs for all devices.
Disadvantages of CSS
 Cross-Browser Compatibility Issues: Different browsers may interpret CSS differently, causing
inconsistencies in design.
 Complexity in Large Projects: As projects grow, CSS can become hard to manage, leading to
cluttered code and style conflicts.
 Limited Dynamic Behavior: CSS is mainly for static design, so it can’t handle complex interactions
or animations without JavaScript
CSS comprises of style rules interpreted by the browser and then applied to the corresponding elements
in your document. A style rule is made of three parts −
 Selector - A selector is an HTML tag at which a style will be applied. This could be any tag like

<html>
<head> <style>
/* Parent selector */ body {
background-color: yellow; color: black;
} /* Child selector */
h2 { background-color: green;
color: white; }
</style> </head>
<body>
<h2>GeeksForGeeks</h2> </body>
</html>

<h1> or <table> etc.


 Property - A property is a type of attribute of HTML tag. Put simply, all the HTML attributes are
converted into CSS properties. They could be color, border etc.
 Value - Values assigned to properties. For example, the color property can have value
either red or #F1F1F1 etc
You can put CSS Style Rule Syntax as follows:
selector { property: value }
Inheritance: This method determines which style should be applied based on the parent-child
relationship between elements. Styles applied to a parent element will be inherited by its child
elements unless overridden by a more specific style. This method uses the !important keyword to
indicate that a rule should take precedence over all others. However, it is generally considered best
practice to avoid using !important unless absolutely necessary. Inheritance is the mechanism by which
styles are passed from a parent element to its children’s elements. The child element inherits the
styles of its parent element unless the styles are explicitly overridden.
Syntax:
body { /* Parent selector */
/* Styles */ }
p{ /* Child selector */
/* Styles */ }
Example: In this example, we are using the above-explained method.
The background-color of the heading ‘GeeksForGeeks’ will be green and its text color will be white.
The background-color of the body will be yellow, but its text color will be overridden by the child
selector (h2).
Output:

The CSS Text Property


Property Description
color Specifies the color of text
direction Specifies the text direction/writing direction
text-align Specifies the horizontal alignment of text
text-align-last Specifies how to align the last line of a text
unicode-bidi Used together with the direction property to set or return whether the text
should be overridden to support multiple languages in the same document
vertical-align Sets the vertical alignment of an element
text-decoration Sets all the text-decoration properties in one declaration
text-decoration-color Specifies the color of the text-decoration
text-decoration-line Specifies the kind of text decoration to be used (underline, overline, etc.)
text-decoration-style Specifies the style of the text decoration (solid, dotted, etc.)
text-decoration-thickness Specifies the thickness of the text decoration line
text-transform Controls the capitalization of text
letter-spacing Specifies the space between characters in a text
line-height Specifies the line height
text-indent Specifies the indentation of the first line in a text-block
white-space Specifies how to handle white-space inside an element
word-spacing Specifies the space between words in a text
text-shadow Specifies the shadow effect added to text
The CSS Box Model defines how elements are sized, positioned, and rendered on a webpage. When a
browser loads an HTML document, it creates a DOM tree and assigns a box to each element. This box
calculates the element’s dimensions and position relative to its parent or the root <html> element,
ensuring accurate layout and spacing.
Box Model Component Layout
 Content: The area where text or other content is displayed.
 Padding: Space between the content and the element’s border.
 Border: A frame that wraps around the padding and content.
 Margin: Space between the element’s border and neighbouring elements.
The normal flow box layout is the default way that HTML elements are laid out in a web page.
It's a simple, straightforward layout model where elements are placed one after another, either
horizontally or vertically, based on their display type.
Key Characteristics:
 Block-Level Elements:
o By default, block-level elements (like <div>, <p>, <h1> to <h6>, <ul>, <ol>, <li>, etc.) take up the
full width of their containing block. You can set their width, height, margin, and padding.
 Inline Elements:
o By default, inline elements (like <span>, <a>, <strong>, <em>, <img>, etc.) only take up the
width required by their content. margin-left and margin-right are respected. padding is applied,
but it doesn't affect the layout of subsequent content on the same line.
 Inline-Block Elements:
o These elements (like display: inline-block;) behave like inline elements in that they flow
horizontally, but they also behave like block elements in that you can set
their width, height, margin, and padding.
 Containing Block:
o Every element is laid out within a containing block. For elements within the <body>, the initial
containing block is the viewport (the browser window). For other elements, the containing
block is typically the nearest ancestor block-level element whose position is not static (or the
initial containing block if no such ancestor exists).
 Whitespace:
o Whitespace (spaces, tabs, newlines) between inline elements is rendered as a single space. This
can sometimes lead to unexpected gaps between inline-block elements.
How Elements are Positioned:
In the normal flow, elements are positioned in the order they appear in the HTML source code.
1. Block Formatting Context (BFC): Block-level elements participate in a Block Formatting Context
(BFC). Within a BFC, block-level boxes are laid out vertically, one after another, starting from
the top of the containing block. The vertical distance between two sibling boxes is determined
by the margin properties.
2. Inline Formatting Context (IFC): Inline elements participate in an Inline Formatting
Context (IFC). Within an IFC, inline boxes are laid out horizontally, one after another, starting
from the left edge of the containing block. The line breaks when the line box is filled. Example:
<html> <head> <title>Normal Flow Example</title>
<style>
div { border: 1px solid blue; margin: 10px; }
span { border: 1px solid red; padding: 5px; }
</style> </head>
<body> <div>This is the first div.</div>
<div> This is the second div with some
<span>inline text</span> and more text.
</div>
<p>This is a paragraph.</p> </body> </html>
In the normal flow:
 The first div will take up the full width and appear at the top.
 The second div will appear below the first div, also taking up the full width.
 The span inside the second div will flow horizontally within the div.
 The p element will appear below the second div, also taking up the full width.
Limitations of Normal Flow:
 Limited Control Over Positioning: It's difficult to precisely position elements in relation to each
other or in arbitrary locations on the page.
 Column Layouts: Creating multi-column layouts is challenging with just normal flow.
 Overlapping Elements: Normal flow doesn't inherently support overlapping elements.
 Responsiveness: Adapting layouts for different screen sizes often requires more than just
normal flow.
Beyond Normal Flow:
To overcome the limitations of normal flow, CSS provides other layout models:
 Floats: Used to wrap text around elements or create simple multi-column layouts.
 Positioning: Allows for precise positioning of elements using relative, absolute, fixed,
and sticky values.
 Flexbox: A powerful one-dimensional layout model for arranging items in rows or columns.
Excellent for aligning and distributing space among items.
 Grid: A two-dimensional layout model for arranging items in rows and columns. Ideal for
creating complex grid-based layouts.
In summary, the normal flow box layout is the foundation of CSS layout. It dictates how
elements are placed sequentially based on their display type. Understanding normal flow is
crucial before diving into more advanced layout technique
Positioning and other useful Style Properties
You're right to ask about positioning and other useful style properties! While normal flow is the
default, CSS offers a powerful set of properties to control the layout, appearance, and behavior
of elements.
Positioning Properties:
The position property is fundamental to controlling how an element is placed within its
containing block and in relation to other elements.
 position: static;
o Default: This is the default value.
o Behavior: Elements are positioned according to the normal flow.
o Offsets (top, bottom, left, right): These properties have no effect on elements with position:
static;.
 position: relative;
o Behavior: Elements are positioned according to the normal flow first, and then offset relative to
their original position.
o Offsets (top, bottom, left, right): These properties move the element from its normal flow
position. The space occupied by the element in the normal flow is reserved.
o Use Cases: Often used as a containing block for absolutely positioned children, or for minor
adjustments to an element's position without affecting the surrounding layout.
 position: absolute;
o Behavior: Elements are removed from the normal flow. They are positioned relative to
their nearest positioned ancestor (an ancestor with position other than static). If no such
ancestor exists, they are positioned relative to the initial containing block (the viewport).
o Offsets (top, bottom, left, right): These properties define the distance from the edges of the
containing block.
o Use Cases: Creating overlays, modals, dropdown menus, or placing elements in specific
locations regardless of the normal flow.
 position: fixed;
o Behavior: Elements are removed from the normal flow. They are positioned relative to
the viewport and remain in that position even when the page is scrolled.
o Offsets (top, bottom, left, right): These properties define the distance from the edges of the
viewport.
o Use Cases: Creating fixed headers, footers, sidebars, or "back to top" buttons.
 position: sticky;
o Behavior: Elements are positioned according to the normal flow until they reach a specified
offset from the viewport. At that point, they become "sticky" and behave like position:
fixed; within their containing block.
o Offsets (top, bottom, left, right): These properties define the threshold at which the element
becomes sticky.
o Use Cases: Creating sticky navigation bars or elements that stay visible as the user scrolls.
Other Useful Style Properties:
Beyond positioning, there's a vast array of CSS properties to control various aspects of element
appearance and behavior. Here are some of the most commonly used and useful ones:
Sizing and Spacing:
 width and height: Sets the width and height of an element. Can be in pixels, percentages, ems,
rems, etc.
 max-width and max-height: Sets the maximum width and height. Prevents the element from
exceeding these dimensions.
 min-width and min-height: Sets the minimum width and height. Ensures the element is at least
these dimensions.
 margin: Sets the space outside the element's border. Can be set for all sides at once or
individually (margin-top, margin-right, margin-bottom, margin-left). Shorthand allows setting
multiple sides.
 padding: Sets the space inside the element's border, between the content and the border.
Similar syntax to margin.
 box-sizing: Controls how the width and height properties are calculated.
o content-box (default): width and height apply only to the content area. Padding and border are
added outside.
o border-box: width and height include padding and border. This is often preferred as it makes
layout calculations more intuitive.
Typography:
 font-family: Sets the font for the text. Can specify multiple fonts as a fallback.
 font-size: Sets the size of the font. Can be in pixels, ems, rems, percentages, etc.
 font-weight: Sets the boldness of the font (e.g., normal, bold, 100 to 900).
 font-style: Sets the style of the font (e.g., normal, italic, oblique).
 text-align: Aligns the text within the element (e.g., left, right, center, justify).
 line-height: Sets the spacing between lines of text.
 color: Sets the color of the text.
Visuals:
 background-color: Sets the background color of an element.
 background-image: Sets a background image.
 background-repeat: Controls if and how a background image repeats (e.g., no-repeat, repeat-
x, repeat-y, repeat).
 background-position: Sets the starting position of a background image.
 background-size: Controls the size of a background image (e.g., auto, cover, contain).
 border: Sets the border around an element. Shorthand combines border-width, border-style,
and border-color. Can also be set for individual sides.
 border-radius: Rounds the corners of an element's border.
 box-shadow: Adds a shadow effect to an element.
 opacity: Sets the transparency of an element (from 0 to 1).
Layout and Display:
 display: Controls how an element is displayed (e.g., block, inline, inline-block, none, flex, grid).
This is a very important property for controlling layout.
 overflow: Controls what happens when content overflows the element's box
(e.g., visible, hidden, scroll, auto).
 float: Used to push an element to the left or right, allowing content to wrap around it. Less
common for main layouts now with Flexbox and Grid.
 clear: Used to prevent elements from being affected by floats.
Interactivity and Behavior:
 cursor: Changes the mouse cursor when hovering over an element (e.g., pointer, text, wait).
 pointer-events: Controls whether an element responds to mouse events (e.g., auto, none).
 transition: Creates smooth animations for changes in CSS properties.
 animation: Creates more complex animations.
Other Useful Properties:
 z-index: Controls the stacking order of elements that overlap. Higher values appear on top.
Only applies to positioned elements (relative, absolute, fixed, sticky).
 visibility: Controls whether an element is visible (visible) or hidden (hidden). Unlike display:
none;, visibility: hidden; still occupies space in the layout.
 outline: Draws an outline around an element, typically used for accessibility to indicate focus.
Unlike border, it doesn't take up space.
Choosing the Right Properties:
The best set of properties to use depends heavily on the desired layout and visual effect.
Understanding the normal flow and then how positioning and other properties modify that flow
is key to mastering CSS layout.
Start by understanding the fundamental display property and how it affects normal flow. Then,
explore positioning properties for more precise control. Finally, leverage the vast array of other
style properties to fine-tune the appearance and behavior of your elements.
CSS3 (Cascading Style Sheets Level 3) is the latest evolution of the CSS language. It's not a
single, monolithic specification but rather a collection of modular specifications. This modularity
allows for faster development and adoption of new features.
1. Modules and Modularity:
 Breaking Down the Specification: CSS3 is divided into modules, each addressing a specific area
of styling (e.g., Selectors, Box Model, Backgrounds and Borders, Text Effects, Transformations,
Transitions, Animations, Grid, Flexbox, etc.). This makes the specification more manageable and
allows browsers to implement and support features independently.
2. Selectors:
 More Powerful Selectors: CSS3 introduced a range of new and more sophisticated selectors,
allowing developers to target elements with greater precision:
o Attribute Selectors: Select elements based on their attributes and their values
(e.g., [target="_blank"], [href^="https"]).
o Structural Pseudo-classes: Select elements based on their position within the document tree
(e.g., :first-child, :last-child, :nth-child(), :nth-last-child(), :only-child, :first-of-type, :last-of-type, :
nth-of-type(), :nth-last-of-type(), :only-of-type).
o UI Element States Pseudo-classes: Select elements based on their user interface state
(e.g., :checked, :disabled, :enabled, :read-only, :read-write).
o Negation Pseudo-class (:not()): Select elements that do not match a given selector
(e.g., div:not(.important)).
o Target Pseudo-class (:target): Select the element that is the target of the current URL fragment.
 Combinators: While not entirely new, CSS3 solidified the use of combinators like the general
sibling combinator (~) and the adjacent sibling combinator (+).
3. Visual Effects and Enhancements:
 Border-radius: Easily round the corners of elements.
 Box-shadow: Add shadow effects to elements.
 Text-shadow: Add shadow effects to text.
 Multiple Backgrounds: Apply multiple background images to a single element.
 Background-size: Control the size of background images (cover, contain, specific dimensions).
 Background-origin and Background-clip: Control the positioning area and painting area of
background images.
 RGBA and HSLA Colors: Use alpha transparency in colors.
 Gradients: Create smooth transitions between colors (linear and radial).
 Opacity: Control the transparency of an element.
4. Layout and Positioning:
 Flexbox (Flexible Box Layout): A one-dimensional layout model designed for arranging items in
a row or column and distributing space among them. Excellent for creating responsive
navigation bars, aligning items, and distributing content evenly.
 Grid (CSS Grid Layout): A powerful two-dimensional layout model for arranging items in rows
and columns. Ideal for creating complex, grid-based layouts for entire pages or specific
components.
 Multi-column Layout: Create magazine-like layouts with text flowing into multiple columns.
 Box-sizing: Control how the width and height properties are calculated, including padding and
border.
5. Transformations, Transitions, and Animations:
 2D and 3D Transformations: Rotate, scale, skew, and translate elements in 2D and 3D space
using the transform property.
 Transitions: Create smooth animations for changes in CSS property values over a specified
duration using the transition property.
 Animations: Create more complex and multi-step animations using the @keyframes rule and
the animation property.
6. Text Effects and Typography:
 Web Fonts (@font-face): Embed custom fonts into your web pages, allowing for greater
typographic control without relying on user-installed fonts.
 Text Overflow: Control how overflowing text is handled (e.g., ellipsis to indicate truncated
text).
 Word Wrap / Break Word: Control how long words are broken to prevent overflow.
 Writing Modes: Support different writing directions (e.g., vertical text).
7. Responsive Web Design Features:
 Media Queries: Apply different styles based on the characteristics of the device or viewport,
such as screen width, height, orientation, and resolution. This is a cornerstone of responsive
web design.
 Viewport Units (vw, vh, vmin, vmax): Units relative to the viewport dimensions, useful for
creating elements that scale with the browser window.
8. Other Notable Features:
 Generated Content (::before, ::after): Insert content before or after an element using CSS.
 Attribute Selectors: As mentioned earlier, a significant improvement for targeting elements
based on attributes.
 Pseudo-elements (e.g., ::selection): Style parts of an element that are not explicitly in the
HTML, like the selected text.
 Custom Properties (CSS Variables): Define reusable values (like colors or font sizes) that can be
used throughout your stylesheet. This improves maintainability and reduces repetition.
Benefits of CSS3:
 Richer Visuals: Allows for more sophisticated and visually appealing designs without relying as
heavily on images or JavaScript.
 Improved Layout Control: Flexbox and Grid provide powerful and flexible ways to create
complex layouts.
 Enhanced Performance: Many visual effects and animations can be achieved with CSS3, which
is often more performant than JavaScript-based solutions, as browsers can optimize them.
 Better Responsiveness: Media queries and viewport units are essential for creating websites
that adapt to different devices.
 Increased Developer Productivity: New selectors and features make it easier to target and style
elements.
 Modularity and Future-Proofing: The modular nature allows for continuous development and
Static Web Pages:
 Definition: Static web pages are those whose content is fixed and
does not change unless the developer manually updates the HTML,
CSS, or images. The content is pre-generated on the server and sent
to the user's browser exactly as it is stored.
 Characteristics:
o Content is fixed Fast loading Simple to build
Limited interactivity
o Good for: Websites with content that doesn't change frequently,
like brochures, portfolios, or documentation.
 How they work (without JavaScript): When a user requests a
static page, the server simply retrieves the corresponding HTML file
and sends it to the browser. The browser then renders the HTML and
applies any linked CSS.
Dynamic Web Pages:
 Definition: Dynamic web pages are those whose content can
change based on various factors, such as user interaction, data from
a database, the time of day, or other external sources. The content
is often generated or modified on the server or in the user's browser
when the page is requested or interacted with.
 Characteristics:
o Content is variable Higher interactivity More complex
to buildCan be slower to load initially Good for: E-commerce
sites, social media platforms, web applications, blogs, and any site
where content needs to be personalized or updated frequently.
 Static pages: Content is fixed, pre-generated. JavaScript adds
client-side interactivity after loading.
 Dynamic pages: Content can change, often generated or modified
on the server or client. JavaScript is essential for complex
interactivity, data fetching, and building modern web applications.
JavaScript empowers developers to transform static HTML and CSS
into engaging and responsive user experiences, making it a
cornerstone of modern web development for both static
enhancements and full-fledged dynamic applications.

You might also like