Understanding CSS Basics and Stylesheets
Understanding CSS Basics and Stylesheets
CSS stands for “Cascading Style Sheet”. It is used to style HTML Documents. CSS simplifies
the process of making web pages presentable. It describes how web pages should look it
prescribes colors, fonts, spacing, and much more.
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, describing how a
webpage should look by prescribing colors, fonts, spacing, and posi�oning. CSS provides
developers and designers with powerful control over the presenta�on of HTML elements.
HTML uses tags and CSS uses rulesets. CSS styles are applied to the HTML element using
selectors. CSS is easy to learn and understand, but it provides powerful control over the
presenta�on of an HTML document.
Why CSS?
• Saves Time: Write CSS once and reuse it across mul�ple HTML pages.
• Easy Maintenance: Change the style globally with a single modifica�on.
• Search Engine Friendly: Clean coding technique that improves readability for search
engines.
• Superior Styles: Offers a wider array of atributes compared to HTML.
• Offline Browsing: CSS can store web applica�ons 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 declara�on block.
• Selector: Targets specific HTML elements to apply styles.
• Declara�on: Combina�on of a property and its corresponding value.
// HTML Element
<h1>GeeksforGeeks</h2>
// CSS Style
h1 { color: blue; font-size: 12px; }
Where -
Selector - h1
Declara�on - { color: blue; font-size: 12px; }
• The selector points to the HTML element that you want to style.
• The declara�on block contains one or more declara�ons separated by semicolons.
• Each declara�on includes a CSS property name and a value, separated by a colon.
1
CSS STYLESHEETS
Crea�ng a CSS stylesheet is fundamental to styling your web pages, ensuring consistency,
maintainability, and a separa�on of concerns between content (HTML) and presenta�on
(CSS). This guide will walk you through the process of crea�ng a CSS stylesheet, covering
everything from the basics to best prac�ces and advanced techniques.
1. What is a CSS Stylesheet?
A CSS (Cascading Style Sheets) stylesheet is a file containing a set of rules that define how
HTML elements should be displayed on the screen, paper, or other media. Stylesheets allow
you to control the layout, colors, fonts, and overall appearance of your website.
Benefits of Using External Stylesheets
• Separa�on of Concerns: Keeps HTML structure separate from styling, making both
easier to manage.
• Reusability: Apply the same styles across mul�ple pages, ensuring consistency.
• Maintainability: Update styles in one place without modifying every HTML file.
• Performance: Browsers cache external stylesheets, reducing load �mes on
subsequent page visits.
Methods to Apply CSS to HTML
There are three primary ways to apply CSS to HTML:
1. External Stylesheet
2. Internal Stylesheet
3. Inline Styles
Each method has its use cases, but using an external stylesheet is generally recommended
for larger projects due to beter maintainability and reusability.
1. External Stylesheet
An external stylesheet is a separate .css file that contains all your CSS rules. This method is
ideal for styling mul�ple web pages consistently.
Advantages:
• Reusability: The same stylesheet can be linked to mul�ple HTML files.
• Maintainability: Easier to manage and update styles from a single loca�on.
• Performance: Browsers cache external stylesheets, reducing load �mes on
subsequent page visits.
How to Use:
• Create a .css file (e.g., [Link]).
• Link it to your HTML using the <link> tag within the <head> sec�on.
2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<�tle>External Stylesheet Example</�tle>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph styled using an external stylesheet.</p>
</body>
</html>
2. Internal Stylesheet
An internal stylesheet is embedded within an HTML document using the <style> tag inside
the <head> sec�on. This method is suitable for single-page documents or specific styles that
are not reused elsewhere.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<�tle>Internal Stylesheet Example</�tle>
<style>
body {
background-color: #f0f0f0;
}
h1 {
color: blue;
}
</style>
</head>
<body>
3
<h1>Hello, World!</h1>
<p>This paragraph is styled using an internal stylesheet.</p>
</body>
</html>
3. Inline Styles
Inline styles are applied directly to HTML elements using the style atribute. This method is
generally discouraged for maintaining clean and scalable code but can be useful for quick,
specific style changes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<�tle>Inline Styles Example</�tle>
</head>
<body>
<h1 style="color: green;">Hello, World!</h1>
<p style="font-size: 18px;">This paragraph is styled using an inline style.</p>
</body>
</html>
Crea�ng an External Stylesheet
Crea�ng and linking an external stylesheet involves a few simple steps:
1. Create the CSS File:
o Open your preferred text editor or IDE.
o Create a new file and save it with a .css extension, e.g., [Link].
2. Add CSS Rules:
o Write your CSS rules in the .css file. For example:
/* [Link] */
body {
font-family: Arial, sans-serif;
background-color: #ffffff;
color: #333333;
4
margin: 0;
padding: 0;
}
h1 {
color: #2c3e50;
text-align: center;
margin-top: 50px;
}
p{
line-height: 1.6;
margin: 20px;
}
3. Link the CSS File to Your HTML:
• Use the <link> tag in the <head> sec�on of your HTML file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<�tle>External Stylesheet Example</�tle>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>Welcome to My Website</h1>
<p>This is a sample paragraph styled using an external stylesheet.</p>
</body>
</html>
Basic CSS Syntax
CSS syntax consists of selectors and declara�on blocks:
selector {
property: value;
property: value;
5
/* ... more proper�es */
}
2. CSS Selectors
Selectors target HTML elements to apply styles. Here are some common selectors:
1. Element Selector:
o Targets all instances of an element.
o Example: p { ... } targets all <p> elements.
2. Class Selector:
o Targets elements with a specific class atribute.
o Syntax: .classname { ... }
o Example:
CSS:
.highlight {
background-color: yellow;
}
HTML:
<p class="highlight">This paragraph is highlighted.</p>
3. ID Selector:
• Targets a unique element with a specific id atribute.
6
• Syntax: #idname { ... }
• Example:
CSS:
#main-header {
font-size: 24px;
}
HTML:
<h1 id="main-header">Welcome!</h1>
1. Atribute Selector:
o Targets elements based on atributes.
o Example:
CSS code
a[href^="htps"] {
color: green;
}
This targets all <a> elements with an href atribute that starts with "htps".
2. Pseudo-class Selector:
o Targets elements in a specific state.
o Example:
Css code
a:hover {
text-decora�on: underline;
}
3. Grouping Selectors:
o Apply the same styles to mul�ple selectors.
o Example:
css code
h1, h2, h3 {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
4. Descendant Selector:
7
o Targets elements nested within other elements.
o Example:
Css code
nav ul li {
display: inline-block;
margin-right: 10px;
}
Organizing Your Stylesheet
For beter maintainability and readability, organizing your CSS is crucial, especially as your
project grows. Here are some �ps:
1. Use Comments:
o Add comments to explain sec�ons of your stylesheet.
css code
/* Typography */
body {
font-family: Arial, sans-serif;
}
/* Header Styles */
header {
background-color: #333;
color: #fff;
padding: 20px;
}
2. Consistent Forma�ng:
o Use consistent indenta�on, spacing, and casing (e.g., kebab-case for class
names).
3. Modularize Your CSS:
o Break your CSS into sec�ons based on components or layout areas (e.g.,
header, footer, naviga�on).
4. Use a Naming Conven�on:
8
o Adopt a naming conven�on like BEM (Block Element Modifier) to create
scalable and understandable class names.
Example (BEM):
css code
/* Block */
.card { ... }
/* Element */
.card__�tle { ... }
.card__descrip�on { ... }
/* Modifier */
.card--featured { ... }
5. Avoid Over-Specificity:
o Keep selectors as simple as possible to avoid unnecessary complexity.
CSS Proper�es
CSS (Cascading Style Sheets) is a language used to describe a document's presenta�on and
forma�ng in HTML or XML. It allows web developers to control the appearance of elements
on a web page. Here are some commonly used CSS proper�es. A CSS property styles an
aspect of an HTML element.
There are many CSS proper�es you can specify for different HTML elements. These CSS
proper�es are covered in their own texts.
1. Background: Specifies the background color or image of an element.
o The color fills the space that is not covered by the image.
o url("/img/css/sunfl[Link]") points to the background image.
o no-repeat specifies that the background image is not repeated.
o right places the background image to the right of the element.
o Background color: Sets the background color.
.my-element {
background-color: #f1f1f1;
}
9
o Background-image: Sets the background image.
.my-element {
background-image: url('[Link]');
}
o Background-repeat: Determines if/how the background image should repeat.
.my-element {
background-repeat: no-repeat;
}
o Background-posi�on: Sets the star�ng posi�on of the background image.
.my-element {
background-posi�on: center;
}
2. Color: Sets the text color.
o Color: Sets the color of the text.
.my-element {
color: #333333;
}
3. Typography: Controls the font proper�es.
o Font-family: Specifies the font family.
.my-element {
font-family: Arial, sans-serif;
}
o Font size: Sets the size of the font.
.my-element {
font-size: 16px;
}
o Font-weight: Sets the thickness of the font.
.my-element {
font-weight: bold;
}
o Font-style: Applies italic or oblique style to the font.
10
.my-element {
font-style: italic;
}
4. Margin: Defines the space around an element.
o Margin-top, margin-right, margin-botom, margin-le�: Sets the margin for each side
of the element.
.my-element {
margin: 10px 20px 15px 5px;
}
5. Padding: Specifies the space between an element's content and border.
o Padding-top, padding-right, padding-botom, padding-le�: Sets the padding for each
side of the element.
.my-element {
padding: 10px 20px 15px 5px;
}
6. Border: Sets the proper�es of an element's border.
o Border-width: Specifies the width of the border.
.my-element {
border-width: 2px;
}
o Border-color: Sets the color of the border.
.my-element {
border-color: #cccccc;
}
o Border-style: Determines the style of the border (e.g., solid, dashed, doted).
.my-element {
border-style: dashed;
}
7. Width and Height: Sets the dimensions of an element.
o Width: Sets the width of the element.
.my-element {
11
width: 200px;
}
o Height: Sets the height of the element.
.my-element {
height: 100px;
}
8. Display: Controls how an element is displayed.
o Display: Specifies the display behavior (e.g., block, inline, flex).
.my-element {
display: block;
}
9. Posi�oning: Posi�ons an element rela�ve to its containing element or the browser
window.
o Posi�on: Sets the posi�oning method (e.g., sta�c, rela�ve, absolute, fixed).
.my-element {
posi�on: rela�ve;
}
o Top, right, botom, le�: Sets the posi�on of the element.
.my-element {
top: 10px;
le�: 20px;
}
10. Flexbox: Defines flexible boxes for layout purposes.
o Display: flex: Enables a flex container.
.flex-container {
display: flex;
}
o Flex-direc�on: Specifies the direc�on of flex items (e.g., row, column).
.flex-container {
flex-direc�on: row;
}
12
11. Text Alignment: Sets the alignment of text within an element.
o Text-align: Specifies the horizontal alignment of text (le�, right, center, jus�fy).
.my-element {
text-align: center;
}
12. Text Decora�on: Adds decora�ve effects to text.
o Text-decora�on: Sets the decora�on of text (underline, overline, line-through, none).
.my-element {
text-decora�on: underline;
}
13. Text Transforma�on: Controls the capitaliza�on of text.
o Text-transform: Sets the capitaliza�on of text (none, uppercase, lowercase,
capitalize).
.my-element {
text-transform: uppercase;
}
14. Text Overflow: Determines how text is handled when it overflows its container.
o Text-overflow: Sets text behavior when it exceeds its container's width (ellipsis, clip).
.my-element {
text-overflow: ellipsis;
}
15. Box Shadow: Adds a shadow effect to an element's box.
o Box-shadow: Sets the shadow proper�es (color, horizontal offset, ver�cal offset, blur
radius, spread radius).
.my-element {
box-shadow: 2px 2px 4px rgba (0, 0, 0, 0.5);
}
16. Transi�on: Specifies the transi�on effect for a property.
o Transi�on: Sets the transi�on proper�es (property, dura�on, �ming func�on, delay).
.my-element {
transi�on: background-color 0.3s ease-in-out;
13
}
17. Overflow: Specifies how content that overflows its container should be handled.
o Overflow: Sets the overflow behavior (visible, hidden, scroll, auto).
.my-element {
overflow: hidden;
}
18. Box Sizing: Determines how an element's total width and height are calculated.
o Box-sizing: Sets the sizing behavior (content-box, border-box).
.my-element {
box-sizing: border-box;
}
19. Posi�on: Specifies the posi�oning of an element.
o Posi�on: Sets the posi�oning method (sta�c, rela�ve, absolute, fixed).
.my-element {
posi�on: absolute;
}
anima�on-itera�on-count: infinite;
anima�on-direc�on: alternate;
}
14
o Efficiency and consistency: Using CSS proper�es, developers can simultaneously
apply styles to mul�ple elements, reducing code duplica�on and improving
efficiency. CSS also provides inheritance and cascading rules, allowing consistent
styling across a website or specific elements.
o Ease of maintenance: With CSS proper�es, making changes to the styling of a
website becomes more manageable. Developers can easily update proper�es in a
single CSS file, and the changes will be automa�cally reflected across all pages that
reference that stylesheet, ensuring consistency and reducing maintenance efforts.
o Accessibility: CSS proper�es offer accessibility benefits by allowing developers to
control text contrast, font sizes, and element visibility. This enables the crea�on of
web pages that are more readable and usable for individuals with visual impairments
or other accessibility needs.
o Anima�on and interac�vity: CSS proper�es can add anima�on and interac�vity to
web elements. With proper�es like transi�ons, transforms, and anima�ons,
developers can create engaging user experiences by adding movement, hover
effects, and transi�ons between different states of an element.
o Performance op�miza�on: Proper use of CSS proper�es can improve website
performance. By op�mizing proper�es like image sizes, reducing unnecessary styles,
and u�lizing CSS preprocessors or minifica�on techniques, developers can minimize
file sizes, reduce page load �mes, and enhance overall performance.
o Modularity and reusability: CSS proper�es promote modularity by allowing
developers to define reusable styles and apply them to mul�ple elements
throughout a website. This promotes code reusability, reduces redundancy, and
makes maintaining a consistent design across different pages and sec�ons easier.
15
div {
margin: 10px;
padding: 20px;
}
• display property: Controls how an element behaves in the layout. The default for
block elements is display: block;, but you can switch it to other types, like inline,
inline-block, flex, grid, etc.
div {
display: flex;
}
• posi�on property: Determines how an element is posi�oned on the page. Common
values are sta�c (default), rela�ve, absolute, fixed, and s�cky.
div {
posi�on: absolute;
top: 50px;
le�: 100px;
}
Example:
Html code
<div class="block-element">This is a block element</div>
<style>
.block-element {
width: 200px;
height: 100px;
margin: 20px auto;
background-color: lightblue;
padding: 10px;
posi�on: rela�ve;
}
</style>
2. CSS Display and Block-Level Layout
16
In addi�on to simple block elements, you can also modify layouts using CSS proper�es like
display: flex; for flexbox layouts or display: grid; for grid layouts.
Flexbox Example:
Css code
.container {
display: flex;
jus�fy-content: space-between;
}
.block1, .block2 {
width: 45%;
height: 100px;
background-color: coral;
}
Html code
<div class="container">
<div class="block1">Block 1</div>
<div class="block2">Block 2</div>
</div>
3. Inline Elements vs Block Elements
Inline elements, like <span>, <a>, and <img>, do not start on a new line and only take up as
much width as their content. You can change an inline element to a block element using
display: block.
Example:
Css code
a{
display: block;
width: 200px;
background-color: lightgreen;
}
Html code
<a href="#">This is a link styled as a block element</a>
17
4. Block Object Layouts
Objects like images, forms, and embedded elements behave similarly to block elements in
certain contexts, especially when controlling their size and layout.
Example: Image as a Block Element
Css code
img {
display: block;
width: 100%;
height: auto;
}
CSS Lists
The List in CSS specifies the lis�ng of the contents or items in a par�cular manner i.e., it can
either be organized orderly or unorder way, which helps to make a clean webpage. It can be
used to arrange the huge with a variety of content as they are flexible and easy to manage.
The default style for the list is borderless.
Types of Lists in CSS
The list can be categorized into 2 types:
• Unordered List: In unordered lists, the list items are marked with bullets i.e. small
black circles by default.
• Ordered List: In ordered lists, the list items are marked with numbers and an
alphabet.
Proper�es of CSS List
We have the following CSS lists proper�es, which can be used to control the CSS lists:
• list-style-type: This property is used to specify the appearance (such as disc,
character, or custom counter style) of the list item marker.
• list-style-image: This property is used to set the images that will be used as the list
item marker.
• list-style-posi�on: It specifies the posi�on of the marker box with respect to the
principal block box.
• list-style: This property is used to set the list style.
Now, we will learn more about these proper�es with examples.
List Item Marker
This property specifies the type of item marker i.e. unordered list or ordered. The list-style-
type property specifies the appearance of the list item marker (such as a disc, character, or
custom counter style) of a list item element. Its default value is a disc.
18
Syntax:
list-style-type: value;
The following value can be used:
decimal Numbers the list items sequen�ally, star�ng from 1 (e.g., 1, 2, 3…).
decimal-leading-
Similar to decimal, but adds leading zeroes (e.g., 01, 02, 03…).
zero
lower-roman Uses lowercase Roman numerals for list markers (e.g., i, ii, iii…).
upper-alpha Marks ordered list items with uppercase leters (e.g., A, B, C…).
19
<html>
<head>
<style>
ul.a {
list-style-type: square;
}
ol.c {
list-style-type: lower-alpha;
}
</style>
</head>
<body>
<h2>
GeeksforGeeks
</h2>
<p> Unordered lists </p>
<ul class="a">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
<ul class="b">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
<p> Ordered Lists </p>
<ol class="c">
<li>one</li>
<li>two</li>
20
<li>three</li>
</ol>
<ol class="d">
<li>one</li>
<li>two</li>
<li>three</li>
</ol>
</body>
</html>
Output:
21
<head>
<�tle> CSS list-style-image Property </�tle>
<style>
ul {
list-style-image:
url("htps://[Link]/wp-content/uploads/lis�[Link]");
}
</style>
</head>
<body>
<h1>
GeeksforGeeks
</h1>
<p> Unordered lists </p>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</body>
</html>
Output:
22
This example showcases how to apply mul�ple CSS styling proper�es to an unordered list.
The list-style is set to square, while the background color is styled with pink, and padding is
added to create space around the list items, enhancing the overall visual appeal.
HTML
<!DOCTYPE html>
<html>
<head>
<style>
ul.a {
list-style: square;
background: pink;
padding: 20px;
}
</style>
</head>
<body>
<h2>
GeeksforGeeks
</h2>
<p> Unordered lists </p>
<ul class="a">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</body>
</html>
Output:
23
CSS Tables
A table in CSS is used to style HTML table elements, allowing data to be arranged in rows
and columns or more complex structures in an organized manner. Tables play a important
role in communica�on, research, and data analysis. The table-layout property in CSS is
par�cularly useful for controlling the layout of table cells, rows, and columns.
This ar�cle explores various CSS proper�es that can be applied to HTML tables, including
border styling, border collapse, border spacing, cap�on side, empty cells, and table layout.
CSS Table Proper�es
1. Border
The border property is used to specify borders for table elements.
Syntax:
border: table_width table_color;
Example 1: This example describes the CSS Table to apply the border property.
HTML
<!DOCTYPE html>
<html>
<head>
<style>
body {
text-align: le�;
}
h1 {
color: green;
}
24
table,
th,
td {
25
2. Border Collapse
The border-collapse property tells us whether the browser should control the appearance of
the adjacent borders that touch each other or whether each cell should maintain its style.
Syntax:
border-collapse: collapse/separate;
Example 2: This example describes the CSS Table by applying the border-collapse property.
HTML
<!DOCTYPE html>
<html>
<head>
<style>
body {
text-align: le�;
}
h1 {
color: green;
}
[Link] {
26
/* Styling border collapse for table one. */
border-collapse: collapse;
}
[Link] {
/* Styling border separate for table two. */
border-collapse: separate;
}
table,
td,
th {
border: 1.5px solid blue;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>borders collapsed:</h2>
<table class="one">
<tr>
<th>Roll Number</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>A_B_C</td>
</tr>
<tr>
<td>2</td>
<td>X_Y_Z</td>
</tr>
</table>
27
<br>
<br>
<h2>borders separated:</h2>
<table class="two">
<tr>
<th>Roll Number</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>A_B_C</td>
</tr>
<tr>
<td>2</td>
<td>X_Y_Z</td>
</tr>
</table>
</body>
</html>
Output:
28
3. Border Spacing
Border Spacing property specifies the space between the borders of the adjacent cells.
Syntax:
border-spacing: value;
Example 3: This example describes the CSS Table by applying the border-spacing property.
HTML
<!DOCTYPE html>
<html>
<head>
<style>
body {
text-align: le�;
29
}
h1 {
color: green;
}
[Link] {
border-collapse: separate;
<body>
<h1>GeeksforGeeks</h1>
<h2>border spacing:</h2>
<table class="one">
<tr>
30
<th>Roll Number</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>A_B_C</td>
</tr>
<tr>
<td>2</td>
<td>X_Y_Z</td>
</tr>
</table>
<br>
<br>
<h2>border spacing:</h2>
<table class="two">
<tr>
<th>Roll Number</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>A_B_C</td>
</tr>
<tr>
<td>2</td>
<td>X_Y_Z</td>
</tr>
</table>
</body>
</html>
31
Output:
4. Cap�on Side
Cap�on Side property is used for controlling the placement of cap�on in the table. By
default, cap�ons are placed above the table.
Syntax:
cap�on-side: top/botom;
Example 4: This example describes the CSS Table by applying the cap�on-side property to
control the placement of the Table cap�on.
HTML
<!DOCTYPE html>
<html>
<head>
32
<style>
body {
text-align: le�;
}
h1 {
color: green;
}
[Link] {
border-collapse: separate;
border-spacing: 10px;
table,
td,
th {
border: 1.5px solid blue;
}
</style>
</head>
<body>
33
<h1>GeeksforGeeks</h1>
<h2>Cap�on on top:</h2>
<table class="one">
<cap�on>Cap�on at the top of the table.</cap�on>
<tr>
<th>Roll Number</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>A_B_C</td>
</tr>
<tr>
<td>2</td>
<td>X_Y_Z</td>
</tr>
</table>
<br>
<br>
<h2>Cap�on at botom:</h2>
<table class="two">
<cap�on> Cap�on at the botom of the table </cap�on>
<tr>
<th>Roll Number</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>A_B_C</td>
</tr>
<tr>
34
<td>2</td>
<td>X_Y_Z</td>
</tr>
</table>
</body>
</html>
Output:
5. Empty cells
Empty cells property specifies whether or not to display borders and background on empty
cells in a table.
Syntax:
35
empty-cells:show/hide;
Example 5: This example describes the CSS Table by applying the empty-cell property that
specifies whether to display the borders or not in the empty cells in a table.
HTML
<!DOCTYPE html>
<html>
<head>
<style>
body {
text-align: le�;
}
h1 {
color: green;
}
[Link] {
border-collapse: separate;
border-spacing: 10px;
[Link] {
border-collapse: separate;
border-spacing: 10px;
36
table,
td,
th {
border: 1.5px solid blue;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>empty cells hide:</h2>
<table class="one">
<tr>
<th>Roll Number</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>X_Y_Z</td>
</tr>
</table>
<br>
<br>
<h2>empty cells show:</h2>
<table class="two">
<tr>
<th>Roll Number</th>
<th>Name</th>
37
</tr>
<tr>
<td>1</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>X_Y_Z</td>
</tr>
</table>
</body>
</html>
Output:
6. Table layout
38
The Table layout property is used to set up the layout algorithm used for the table.
Syntax:
table-layout:auto/fixed;
Example 6: This example describes the CSS Table by applying the table layout property.
HTML
<!DOCTYPE html>
<html>
<head>
<style>
body {
text-align: le�;
}
h1 {
color: green;
}
[Link] {
width: 80px border-collapse: separate;
border-spacing: 10px;
[Link] {
width: 80px border-collapse: separate;
border-spacing: 10px;
/* Layout of table is fixed. */
table-layout: fixed;
}
table,
td,
39
th {
border: 1.5px solid blue;
width: 80px;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>auto table layout:</h2>
<table class="one">
<tr>
<th>Roll Number</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>A_B_C_D_E_F_G_H_I_J_K_L_M_N_O_P</td>
</tr>
<tr>
<td>2</td>
<td>X_Y_Z</td>
</tr>
</table>
<br>
<br>
<h2>fixed table layout:</h2>
<table class="two">
<tr>
<th>Roll Number</th>
<th>Name</th>
</tr>
40
<tr>
<td>1</td>
<td>A_B_C_D_E_F_G_H_I_J_K_L_M_N_O_P</td>
</tr>
<tr>
<td>2</td>
<td>X_Y_Z</td>
</tr>
</table>
</body>
</html>
Output:
41
CSS provides a range of proper�es to enhance the styling and func�onality of HTML tables.
By understanding and applying proper�es like border, border-collapse, border-spacing,
cap�on-side, empty-cells, and table-layout, web developers can create well-structured and
visually appealing tables.
42
Css code
.box {
background-color: lightgreen;
padding: 20px;
margin-botom: 10px;
}
Key Points about Classes:
• Reusability: Classes can be used on mul�ple elements. For example, you might use
the class .box on several <div> elements to apply consistent styling.
• Usage: Ideal for styling groups of similar elements (like butons, form fields, cards,
etc.).
• Specificity: Class selectors have lower specificity than IDs but can s�ll override more
general styles (like tag selectors).
3. Using IDs and Classes Together
It's common to use both an ID and a class on the same element. This way, you can apply
general styles using the class, and more specific styles using the ID.
Example:
Html code
<div id="main-content" class="content-box">Main Content Area</div>
Css code
#main-content {
background-color: coral;
}
.content-box {
padding: 20px;
border: 1px solid black;
}
In this example:
• The #main-content ID gives the element a background color of coral.
• The .content-box class adds padding and a border. Since the ID has a higher
specificity, it will override any class styles that might conflict.
4. Specificity in CSS
43
CSS applies styles based on specificity, which is a rule that determines which styles are
applied when mul�ple styles target the same element. Here's the specificity ranking:
1. Inline styles (style atribute in HTML): Highest specificity.
2. ID selectors (#id): Second highest.
3. Class selectors, atribute selectors, and pseudo-classes (.class, [atribute], :hover):
Moderate specificity.
4. Element (tag) selectors (div, h1, p): Lowest specificity.
If you had both an ID and class applied to the same element, the ID style would be applied
due to its higher specificity.
Example of Specificity:
Html code
<div id="example" class="highlight">Example Text</div>
Css code
#example {
color: red;
}
.highlight {
color: blue;
}
The text in the <div> will be red because the ID selector (#example) has higher specificity
than the class selector (.highlight).
Class Id
We can apply a class to various elements so that The Id is unique in a page, and we can only apply
it could be numerous �mes on a single page. it to one specific element.
44
The class is assigned to an element and its name The name of the Id starts with the "#" symbol
starts with "." followed by the name of the class. followed by a unique id name.
We can atach mul�ple class selectors to an We can atach only one ID selector to an
element. element.
Syntax: Syntax:
.class{ #id{
// declara�ons of CSS // declara�ons of CSS
} }
45
2. Padding Area
• Surrounds the content area.
• Space within the border box.
• Dimensions are determined by the width and height of the padding box.
3. Border Area
• Lies between the padding and margin.
• Width and height are defined by the border.
4. Margin Area
• Separates the element from adjacent elements.
• Dimensions specified by the margin-box width and height.
46
border: 2px solid black;
padding: 5px;
}
Total Width Calcula�on
Total element width = width + left padding + right padding + left border + right border
• Total width of the element is 94px.
• Total width = 80px (width) + 10px (le� padding + right padding) + 4px (le� border +
right border) = 94px.
Total Height Calcula�on
Total element height = height + top padding + bottom padding + top border + bottom border
• Total height of the element is 84px.
• Total height = 70px (height) + 10px (top padding + botom padding) + 4px (top border
+ botom border) = 84px.
Examples of Box models in CSS
Now, We have learned the working of the CSS Box Model in-depth and now we will see Box
Model examples so that we can properly understand it.
Example 1
This example illustrates the use of the CSS Box model for aligning & displaying it properly.
HTML
<!DOCTYPE html>
<html>
<head>
<�tle>CSS Box Model</�tle>
<style>
.main {
font-size: 36px;
font-weight: bold;
Text-align: center;
}
.gfg {
margin-le�: 60px;
47
border: 50px solid #009900;
width: 300px;
height: 200px;
text-align: center;
padding: 50px;
}
.gfg1 {
font-size: 42px;
font-weight: bold;
color: #009900;
margin-top: 60px;
background-color: #c5c5db;
}
.gfg2 {
font-size: 18px;
font-weight: bold;
background-color: #c5c5db;
}
</style>
</head>
<body>
<div class="main">
CSS Box-Model Property
</div>
<div class="gfg">
<div class="gfg1">
GeeksforGeeks
</div>
<div class="gfg2">
A computer science portal for geeks
</div>
48
</div>
</body>
</html>
Output:
Example 2
This example illustrates the Box Model by implemen�ng the various proper�es.
HTML
<!DOCTYPE html>
<html>
<head>
<style>
.main {
font-size: 32px;
font-weight: bold;
text-align: center;
}
#box {
padding-top: 40px;
width: 400px;
height: 100px;
49
border: 50px solid green;
margin: 50px;
text-align: center;
font-size: 32px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="main">CSS Box-Model Property</div>
<div id="box">GeeksforGeeks</div>
</body>
</html>
Output:
50
• border-width: Specifies the width of the border (can be set individually for each
side).
• border-style: Defines the style of the border (solid, dashed, doted, double, groove,
etc.).
• border-color: Sets the color of the border.
• border-radius: Rounds the corners of the border.
Syntax:
Css code
/* Shorthand to define width, style, and color */
border: 2px solid red;
/* Individual proper�es */
border-width: 2px;
border-style: solid;
border-color: red;
/* Border radius for rounded corners */
border-radius: 10px;
Example:
Html code
<div class="box">Box with Border</div>
Css code
.box {
width: 200px;
padding: 20px;
border: 3px solid blue;
border-radius: 10px; /* Rounded corners */
}
Border on Specific Sides:
You can set the border on individual sides using:
• border-top
• border-right
• border-botom
51
• border-le�
css code
.box {
border-top: 4px dashed green;
border-right: 2px solid black;
border-botom: 6px double red;
border-le�: 5px doted purple;
}
Border Radius:
The border-radius property allows you to round the corners of a border.
Css code
.box {
border: 2px solid black;
border-radius: 15px; /* Makes rounded corners */
}
2. Padding Proper�es
Padding is the space between the content and the element’s border. It ensures that the
content doesn’t touch the border directly.
Common Padding Proper�es:
• padding: Shorthand for se�ng padding on all four sides.
• padding-top: Padding on the top side.
• padding-right: Padding on the right side.
• padding-botom: Padding on the botom side.
• padding-le�: Padding on the le� side.
Syntax:
Css code
/* Padding on all sides (equal) */
padding: 20px;
/* Padding on top and botom, right and le� */
padding: 20px 10px;
/* Padding top, right and le�, botom */
52
padding: 20px 10px 30px;
/* Padding top, right, botom, le� */
padding: 20px 10px 30px 40px;
Example:
html code
<div class="box">Box with Padding</div>
Css code
.box {
width: 200px;
padding: 20px;
border: 2px solid black;
background-color: lightblue;
}
This creates a box with 20px of padding on all sides.
Individual Padding Proper�es:
css code
.box {
padding-top: 20px;
padding-right: 10px;
padding-botom: 30px;
padding-le�: 5px;
}
3. Margin Proper�es
Margin is the space outside the element’s border. It controls the distance between the
current element and neighboring elements.
Common Margin Proper�es:
• margin: Shorthand for se�ng margins on all sides.
• margin-top: Sets the margin on the top side.
• margin-right: Sets the margin on the right side.
• margin-botom: Sets the margin on the botom side.
• margin-le�: Sets the margin on the le� side.
53
Syntax:
Css code
/* Margin on all sides */
margin: 20px;
/* Margin top and botom, right and le� */
margin: 20px 10px;
/* Margin top, right and le�, botom */
margin: 20px 10px 30px;
/* Margin top, right, botom, le� */
margin: 20px 10px 30px 40px;
Example:
Html code
<div class="box">Box with Margin</div>
Css code
.box {
width: 200px;
padding: 20px;
border: 2px solid black;
margin: 30px;
background-color: lightgreen;
}
This adds 30px of space outside the box.
Nega�ve Margins:
Margins can also have nega�ve values to pull an element closer to other elements or even
overlap them.
Css code
.box {
margin-top: -20px;
margin-le�: -10px;
}
54
Example Pu�ng It All Together:
Here’s an example combining border, padding, and margin:
Html code
<div class="box">Box Model Example</div>
Css code
.box {
width: 200px;
padding: 20px; /* Space between content and border */
border: 3px solid black; /* Border around the element */
margin: 30px; /* Space outside the element */
background-color: lightgray; /* Background color inside the box */
}
This will create a box:
• 200px wide with 20px padding.
• A 3px solid black border.
• 30px margin around it.
• A lightgray background color inside the box.
Box Sizing and Total Width/Height Calcula�on
The total width of an element is calculated as:
Css code
Total Width = width + padding-le� + padding-right + border-le� + border-right + margin-le�
+ margin-right
And for height:
Css code
Total Height = height + padding-top + padding-botom + border-top + border-botom +
margin-top + margin-botom
To prevent padding and border from affec�ng the total size of the element, you can use the
box-sizing: border-box; property, which includes padding and borders inside the
width/height.
Css code
.box {
width: 200px;
55
padding: 20px;
border: 5px solid black;
box-sizing: border-box; /* Padding and border included in width */
}
With box-sizing: border-box, the total width remains 200px, even with the padding and
border.
1. Grouping Selectors
Grouping selectors allows you to apply the same styles to mul�ple elements without
repea�ng the CSS proper�es.
Syntax
css code
selector1, selector2, selector3 {
/* shared styles */
}
Example
css code
h1, h2, h3, .�tle {
color: #333;
font-family: 'Arial', sans-serif;
}
Benefits
• Reduces code duplica�on.
• Simplifies maintenance by centralizing common styles.
2. Dimensions
Managing dimensions involves controlling the width, height, padding, margins, and box-
sizing of elements to create a well-structured layout.
Key Proper�es
• Width & Height
56
Css code
.box {
width: 200px;
height: 150px;
}
• Max-Width & Max-Height
Css code
.container {
max-width: 1200px;
max-height: 800px;
}
• Box-Sizing
Css code
.element {
box-sizing: border-box;
}
o border-box includes padding and border in the element's total width and
height.
Responsive Dimensions
Use rela�ve units like %, vw, vh, em, and rem for responsive design.
Css code
.container {
width: 80%;
padding: 2rem;
}
3. Display
The display property controls the layout behavior of elements, determining how they are
rendered in the document flow.
Common Values
• block: Element occupies the full width, starts on a new line.
• inline: Element occupies only the necessary width, does not start on a new line.
57
• inline-block: Combines characteris�cs of block and inline.
• flex: Enables Flexbox layout.
• grid: Enables Grid layout.
• none: Hides the element.
Example
Css code
.navbar {
display: flex;
jus�fy-content: space-between;
align-items: center;
}
Advanced Usage
• Flexbox:
Css code
.container {
display: flex;
flex-direc�on: row;
flex-wrap: wrap;
}
• Grid:
Css code
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
4. Posi�oning
Posi�oning determines how elements are placed in the document. The posi�on property
can take several values, each with different behaviors.
Posi�on Values
• sta�c: Default posi�oning, follows the normal flow.
58
• rela�ve: Posi�oned rela�ve to its normal posi�on.
• absolute: Posi�oned rela�ve to the nearest posi�oned ancestor.
• fixed: Posi�oned rela�ve to the viewport.
• s�cky: Toggles between rela�ve and fixed based on scroll posi�on.
Example
Css code
.header {
posi�on: fixed;
top: 0;
width: 100%;
background-color: #fff;
z-index: 1000;
}
.sidebar {
posi�on: absolute;
le�: 0;
top: 60px;
width: 250px;
}
5. Floa�ng
Floa�ng allows elements to be taken out of the normal flow and placed to the le� or right of
their container, allowing other content to wrap around them.
Syntax
css code
.element {
float: le� | right | none | inherit;
}
Example
css code
.image {
float: le�;
59
margin: 0 15px 15px 0;
}
Clearing Floats
A�er floa�ng elements, use the clear property or clearfix techniques to prevent layout
issues.
Css code
.clearfix::a�er {
content: "";
display: table;
clear: both;
}
6. Alignment
Alignment in CSS involves posi�oning elements along horizontal and ver�cal axes within
their containers.
Text Alignment
Css code
.text-center {
text-align: center;
}
Flexbox Alignment
Css code
.container {
display: flex;
jus�fy-content: center; /* Horizontal alignment */
align-items: center; /* Ver�cal alignment */
}
Grid Alignment
Css code
.grid-container {
display: grid;
place-items: center; /* Centers both horizontally and ver�cally */
60
}
Ver�cal Alignment for Inline Elements
Css code
.image {
ver�cal-align: middle;
}
7. Pseudo-Classes
Pseudo-classes allow you to style elements based on their state or posi�on in the DOM
without adding extra classes or IDs.
Common Pseudo-Classes
• :hover: When the user hovers over an element.
• :ac�ve: When an element is being ac�vated (e.g., clicked).
• :focus: When an element has focus.
• :nth-child(n): Selects the nth child element.
• :first-child, :last-child: Selects the first or last child.
• :not(selector): Selects elements not matching the selector.
Example
css code
buton:hover {
background-color: #0053ba;
cursor: pointer;
}
ul li:nth-child(odd) {
background-color: #f9f9f9;
}
input:focus {
border-color: #4A90E2;
}
Advanced Pseudo-Classes
• :root: Targets the root element of the document.
• :checked: Targets checked input elements.
61
• :disabled: Targets disabled elements.
• :placeholder-shown: Targets input elements showing placeholder text.
8. Naviga�on Bar
Crea�ng an effec�ve naviga�on bar involves using layout techniques, styling, and some�mes
interac�vity to enhance user experience.
Basic Structure
html code
<nav class="navbar">
<ul class="nav-list">
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
CSS with Flexbox
css code
.navbar {
background-color: #333;
}
.nav-list {
display: flex;
list-style: none;
margin: 0;
padding: 0;
}
.nav-list li {
margin: 0;
}
.nav-list a {
display: block;
62
padding: 15px 20px;
color: #fff;
text-decora�on: none;
}
.nav-list a:hover {
background-color: #575757;
}
Responsive Naviga�on
Using media queries to adjust the navbar for different screen sizes.
css code
@media (max-width: 768px) {
.nav-list {
flex-direc�on: column;
display: none; /* Hidden by default */
}
.[Link]�ve .nav-list {
display: flex;
}
/* Toggle buton styles omited for brevity */
}
Advanced Features
• Dropdown Menus:
css code
.nav-list li {
posi�on: rela�ve;
}
.nav-list li .dropdown {
display: none;
posi�on: absolute;
top: 100%;
le�: 0;
63
background-color: #444;
}
.nav-list li:hover .dropdown {
display: block;
}
• S�cky Navbar:
css code
.navbar {
posi�on: s�cky;
top: 0;
z-index: 1000;
}
9. Image Sprites
Image sprites are a technique where mul�ple images are combined into a single file,
reducing HTTP requests and improving page load �mes.
How It Works
• Combine related images (e.g., icons) into one larger image.
• Use CSS background-posi�on to display the specific part of the sprite needed.
Example
html code
<!-- HTML -->
<buton class="icon-btn home">Home</buton>
<buton class="icon-btn search">Search</buton>
css code
/* CSS */
.icon-btn {
width: 50px;
height: 50px;
background-image: url('[Link]');
background-repeat: no-repeat;
border: none;
64
cursor: pointer;
}
.[Link] {
background-posi�on: 0 0;
}
.[Link] {
background-posi�on: -50px 0;
}
Advantages
• Fewer HTTP requests improve performance.
• Consistent caching behavior.
Tools
• Sprite Generators: Tools like SpritePad or Glue.
Modern Alterna�ves
• Icon Fonts and SVGs offer more flexibility and scalability.
• CSS Sprites are s�ll useful in certain scenarios, especially with legacy systems.
10. Atribute Selectors
Atribute selectors allow you to target elements based on their atributes or atribute values,
enabling more precise styling without addi�onal classes or IDs.
Basic Syntax
css code
/* Select elements with the specified atribute */
element[atribute] { ... }
/* Select elements with atribute exactly matching a value */
element[atribute="value"] { ... }
/* Select elements with atribute containing a word */
element[atribute~="value"] { ... }
/* Select elements with atribute star�ng with a value */
element[atribute^="value"] { ... }
/* Select elements with atribute ending with a value */
element[atribute$="value"] { ... }
65
/* Select elements with atribute containing a substring */
element[atribute*="value"] { ... }
Examples
• All Links with target="_blank"
Css code
a[target="_blank"] {
color: red;
}
• Input Fields of Type "text"
css code
input[type="text"] {
border: 1px solid #ccc;
}
• Elements with a data-role Star�ng with "admin"
css code
[data-role^="admin"] {
background-color: #f0f0f0;
}
• Links Containing "example" in href
css code
a[href*="example"] {
text-decora�on: underline;
}
Advanced Usage
• Styling Based on Mul�ple Atributes
css code
input[type="text"][disabled] {
background-color: #e9ecef;
}
• Using Atribute Selectors with Pseudo-Classes
css code
66
a[href^="htps"]:hover {
color: green;
}
CSS COLOR, Crea�ng page layout, and site designs
1. CSS Color
Color is a fundamental aspect of web design, influencing user experience, accessibility, and
brand percep�on. CSS provides various ways to define and manipulate colors to create
visually appealing and accessible websites.
Understanding Color Values
CSS supports mul�ple color formats, each suitable for different scenarios:
1.1. Named Colors
CSS includes a set of predefined color names.
Css code
.element {
color: teal;
background-color: lightgray;
}
Pros:
• Easy to remember and use.
• Good for quick prototypes.
Cons:
• Limited palete (148 named colors).
• Lack of precision for nuanced designs.
1.2. Hexadecimal Colors
Hex codes represent colors using a combina�on of red, green, and blue (RGB) values.
Css code
.element {
color: #1E90FF; /* Dodger Blue */
background-color: #F0F8FF; /* Alice Blue */
}
Shorthand Nota�on:
67
• #RGB (e.g., #0F8)
• #RRGGBB (e.g., #00FF88)
1.3. RGB and RGBA
RGB allows specifying colors using red, green, and blue components, while RGBA adds an
alpha channel for transparency.
Css code
.element {
color: rgb(30, 144, 255); /* Dodger Blue */
background-color: rgba(240, 248, 255, 0.8); /* Semi-transparent Alice Blue */
}
Advantages:
• Greater precision and flexibility.
• RGBA supports transparency for layering effects.
1.4. HSL and HSLA
HSL defines colors using hue, satura�on, and lightness, with HSLA adding an alpha channel.
Css code
.element {
color: hsl(209, 100%, 56%); /* Dodger Blue */
background-color: hsla(208, 100%, 97%, 0.8); /* Semi-transparent Alice Blue */
}
Advantages:
• Intui�ve for adjus�ng color proper�es.
• Easier to create varia�ons (e.g., lighter or darker shades).
1.5. CSS Variables for Colors
CSS variables (custom proper�es) enhance maintainability and theming.
Css code
:root {
--primary-color: #1E90FF;
--secondary-color: #F0F8FF;
}
68
.element {
color: var(--primary-color);
background-color: var(--secondary-color);
}
Benefits:
• Centralized color management.
• Simplifies theme switching and updates.
Color Models
Understanding color models helps in choosing and manipula�ng colors effec�vely.
1.6. RGB (Red, Green, Blue)
Addi�ve color model where colors are created by combining red, green, and blue light.
1.7. HSL (Hue, Satura�on, Lightness)
• Hue: Degree on the color wheel (0-360°).
• Satura�on: Intensity of the color (0%-100%).
• Lightness: Brightness of the color (0%-100%).
1.8. CMYK (Cyan, Magenta, Yellow, Key/Black)
Subtrac�ve color model primarily used in prin�ng.
Note: CMYK is not na�vely supported in CSS but can be simulated using color management
tools or converted to RGB/HSL.
Advanced Color Techniques
1.9. CSS Gradients
Create smooth transi�ons between two or more colors.
Linear Gradient:
Css code
.element {
background: linear-gradient(to right, #1E90FF, #F0F8FF);
}
Radial Gradient:
Css code
.element {
background: radial-gradient(circle, #1E90FF, #F0F8FF);
69
}
1.10. CSS Variables for Theming
Dynamic theming by altering CSS variables.
Css code
:root {
--bg-color: #ffffff;
--text-color: #000000;
}
.dark-theme {
--bg-color: #121212;
--text-color: #ffffff;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
}
Toggle Theme Example:
Html code
<buton onclick="[Link]('dark-theme')">Toggle Dark
Mode</buton>
1.11. Opacity and Transparency
Control element transparency using opacity or rgba/hsla colors.
Css code
.element {
opacity: 0.5; /* Applies to en�re element */
}
.transparent-bg {
background-color: rgba(30, 144, 255, 0.5); /* Only background */
}
1.12. Contrast Ra�os
• WCAG Guidelines:
70
o Normal Text: Minimum contrast ra�o of 4.5:1
o Large Text (≥18pt or 14pt bold): Minimum contrast ra�o of 3:1
Tools:
• WebAIM Contrast Checker
• Contrast Ra�o
1.13. Avoiding Color-Only Indicators
Do not rely solely on color to convey informa�on (e.g., error messages).
Example:
Css code
/* Bad Prac�ce */
.error {
color: red;
}
/* Good Prac�ce */
.error {
color: red;
border: 1px solid red;
background-color: #ffe6e6;
}
2. Crea�ng Page Layouts
Effec�ve page layouts are essen�al for organizing content, enhancing usability, and providing
a seamless user experience. CSS offers various techniques to create responsive and dynamic
layouts.
Tradi�onal Layout Methods
Before modern CSS layout modules, developers relied on older techniques:
2.1. Float-Based Layouts
Using float to posi�on elements side by side.
Css code
.container {
width: 100%;
}
71
.sidebar {
float: le�;
width: 25%;
}
.content {
float: right;
width: 75%;
}
/* Clearing floats */
.container::a�er {
content: "";
display: table;
clear: both;
}
Cons:
• Complex and hacky solu�ons (e.g., clearfix).
• Limited flexibility.
• Poor support for ver�cal alignment and equal-height columns.
2.2. Table-Based Layouts
U�lizing HTML tables for layout purposes.
Note: This approach is discouraged due to seman�c, accessibility, and flexibility issues.
Flexbox
Flexbox (Flexible Box Layout) provides a powerful way to create one-dimensional layouts,
handling alignment, spacing, and distribu�on of items within a container.
2.3. Flexbox Basics
Css code
.container {
display: flex;
flex-direc�on: row; /* or column */
jus�fy-content: space-between; /* horizontal alignment */
align-items: center; /* ver�cal alignment */
72
}
Key Proper�es:
• display: flex;: Defines a flex container.
• flex-direc�on: Row or column orienta�on.
• jus�fy-content: Alignment along the main axis.
• align-items: Alignment along the cross axis.
• flex-wrap: Controls wrapping of flex items.
2.4. Flex Items
Control individual flex items using:
css code
.item {
flex-grow: 1; /* Allows item to grow */
flex-shrink: 1; /* Allows item to shrink */
flex-basis: 200px; /* Ini�al size */
align-self: center; /* Overrides container alignment */
}
Shorthand:
css code
.item {
flex: 1 1 200px; /* flex-grow | flex-shrink | flex-basis */
}
2.5. Responsive Flexbox Layout
Create responsive layouts that adjust based on screen size.
css code
.container {
display: flex;
flex-wrap: wrap;
}
.item {
flex: 1 1 300px;
}
73
@media (max-width: 600px) {
.item {
flex: 1 1 100%;
}
}
CSS Grid
CSS Grid Layout excels at crea�ng two-dimensional layouts, managing both rows and
columns simultaneously.
2.6. Grid Basics
css code
.container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* Three equal columns */
grid-gap: 20px; /* Space between grid items */
}
Key Proper�es:
• display: grid;: Defines a grid container.
• grid-template-columns and grid-template-rows: Define the grid structure.
• grid-gap: Sets spacing between grid items.
• grid-area: Assigns items to specific grid areas.
2.7. Defining Grid Areas
Create named areas for more control.
css code
.container {
display: grid;
grid-template-areas:
"header header"
"sidebar content"
"footer footer";
grid-gap: 10px;
74
}
.header {
grid-area: header;
}
.sidebar {
grid-area: sidebar;
}
.content {
grid-area: content;
}
.footer {
grid-area: footer;
}
HTML Structure:
html code
<div class="container">
<div class="header">Header</div>
<div class="sidebar">Sidebar</div>
<div class="content">Content</div>
<div class="footer">Footer</div>
</div>
2.8. Responsive Grid Layout
Adjust grid based on screen size using media queries.
css code
.container {
display: grid;
grid-template-columns: 1fr;
}
@media (min-width: 600px) {
.container {
grid-template-columns: 1fr 3fr;
75
}
}
Responsive Design
Responsive design ensures that layouts adapt seamlessly across various devices and screen
sizes.
2.9. Mobile-First Approach
Design for smaller screens first, then enhance for larger screens.
css code
/* Mobile styles */
.container {
display: flex;
flex-direc�on: column;
}
/* Tablet and above */
@media (min-width: 768px) {
.container {
flex-direc�on: row;
}
}
/* Desktop and above */
@media (min-width: 1024px) {
.container {
max-width: 1200px;
margin: 0 auto;
}
}
2.10. Fluid Layouts
Use rela�ve units to create flexible layouts.
css code
.container {
width: 90%;
76
max-width: 1200px;
margin: 0 auto;
}
.image {
width: 100%;
height: auto;
}
2.11. Media Queries
Apply styles based on device characteris�cs.
css code
@media (max-width: 600px) {
.navbar {
display: none;
}
}
@media (min-width: 601px) {
.navbar {
display: flex;
}
}
3. Site Designs
Site design encompasses the overall visual and func�onal aspects of a website, ensuring it is
both aesthe�cally pleasing and user-friendly. CSS is instrumental in bringing these designs to
life.
Design Principles
Adhering to fundamental design principles ensures a cohesive and effec�ve website.
3.1. Balance
Achieve visual equilibrium by distribu�ng elements evenly across the layout.
• Symmetrical Balance: Mirrored elements on either side of an axis.
• Asymmetrical Balance: Different elements that have equal visual weight.
3.2. Contrast
77
Use contras�ng colors, sizes, and shapes to highlight important elements and create visual
interest.
Css code
.buton-primary {
background-color: #1E90FF; /* High contrast */
color: #ffffff;
}
.buton-secondary {
background-color: #f0f0f0; /* Low contrast */
color: #333333;
}
3.3. Hierarchy
Establish a clear hierarchy to guide users through the content.
• Typography: Use varying font sizes and weights.
• Spacing: Adjust margins and padding to create separa�on.
• Color: Highlight key elements with dis�nct colors.
3.4. Consistency
Maintain consistent styles, colors, and layouts across the site to enhance usability and brand
iden�ty.
3.5. Alignment
Ensure elements are properly aligned to create a structured and organized layout.
Typography
Typography significantly impacts readability and the overall aesthe�c of a website.
3.6. Choosing Fonts
• Web-Safe Fonts: Arial, Verdana, Times New Roman, etc.
• Google Fonts: Wide variety of free fonts.
• Custom Fonts: Use @font-face or services like Adobe Fonts.
Css code
body {
font-family: 'Roboto', sans-serif;
}
78
3.7. Font Proper�es
Control the appearance of text with various CSS proper�es.
css code
h1 {
font-size: 2.5rem;
font-weight: 700;
line-height: 1.2;
color: #333333;
}
p{
font-size: 1rem;
line-height: 1.6;
color: #666666;
}
Key Proper�es:
• font-family
• font-size
• font-weight
• line-height
• leter-spacing
• text-transform
3.8. Responsive Typography
Adjust font sizes based on viewport size for op�mal readability.
css code
h1 {
font-size: 2rem;
}
@media (min-width: 768px) {
h1 {.;
font-size: 3rem;
}
79
}
Advanced Techniques:
• Viewport Units:
css code
h1 {
font-size: 5vw;
}
• Clamp Func�on:
css code
h1 {
font-size: clamp(1.5rem, 2.5vw, 3rem);
}
Visual Hierarchy
Organize content to guide users through the site effec�vely.
3.9. Using Size and Scale
Larger elements draw more aten�on, signaling their importance.
css code
.header {
font-size: 2.5rem;
}
.sub�tle {
font-size: 1.5rem;
}
3.10. Color and Contrast
Highlight key elements with dis�nct colors and sufficient contrast.
css code
.buton-primary {
background-color: #1E90FF;
color: #ffffff;
}
80
.buton-secondary {
background-color: #f0f0f0;
color: #333333;
}
3.11. Spacing and Layout
Use white space strategically to separate content and avoid cluter.
css code
.sec�on {
padding: 60px 20px;
margin-botom: 40px;
}
Theming and Branding
Reflect brand iden�ty through consistent styling and theming.
3.12. Color Schemes
Choose color paletes that align with the brand and evoke desired emo�ons.
• Monochroma�c: Varia�ons of a single color.
• Analogous: Colors adjacent on the color wheel.
• Complementary: Opposite colors on the color wheel.
• Triadic: Three colors evenly spaced on the color wheel.
Example:
css code
:root {
--primary-color: #1E90FF;
--secondary-color: #FFD700;
--accent-color: #FF4500;
}
3.13. Consistent UI Components
Design reusable UI components with consistent styles.
css code
.buton {
padding: 10px 20px;
81
border: none;
border-radius: 4px;
cursor: pointer;
}
.buton-primary {
background-color: var(--primary-color);
color: #ffffff;
}
.buton-secondary {
background-color: var(--secondary-color);
color: #333333;
}
3.14. Branding Elements
Incorporate logos, icons, and other branding elements seamlessly into the design.
css code
.logo {
width: 150px;
height: auto;
}
CSS Frameworks and Preprocessors
Leverage frameworks and preprocessors to streamline design and development.
3.15. CSS Frameworks
Popular Frameworks:
• Bootstrap: Comprehensive framework with pre-designed components.
• Tailwind CSS: U�lity-first framework for rapid styling.
• Bulma: Modern framework based on Flexbox.
Example with Tailwind CSS:
html code
<buton class="bg-blue-500 text-white font-bold py-2 px-4 rounded">
Buton
</buton>
82
3.16. CSS Preprocessors
Benefits:
• Variables and mixins for reusable styles.
• Nested syntax for beter organiza�on.
• Advanced func�onali�es like func�ons and opera�ons.
Popular Preprocessors:
• Sass (SCSS):
scss
code
$primary-color: #1E90FF;
.buton {
background-color: $primary-color;
color: #ffffff;
&:hover {
background-color: darken($primary-color, 10%);
}
}
• LESS:
less
code
@primary-color: #1E90FF;
.buton {
background-color: @primary-color;
color: #ffffff;
&:hover {
background-color: darken(@primary-color, 10%);
}
}
• Stylus:
stylus
Copy code
83
primary-color = #1E90FF
.buton
background-color: primary-color
color: #ffffff
&:hover
background-color: darken(primary-color, 10%)
Note: Modern CSS has incorporated many features that were once exclusive to
preprocessors, reducing the necessity but not elimina�ng their usefulness.
84