Chapter 6: Full Stack JavaScript Bootcamp Revision Class – Mastering CSS Fundamentals
Table of Contents
Introduction to CSS
What is CSS?
Importance of CSS in Web Development
Overview of CSS Integration Methods
Three Ways to Link CSS
Inline CSS
Internal CSS
External CSS
Priority of CSS Methods
How CSS Works
Selectors
Declarations (Properties and Values)
CSS Selectors Explained
Universal Selectors
Individual Selectors
Class and ID Selectors
Grouping Selectors
Advanced Selectors
Attribute Selectors
Pseudo-Classes and Pseudo-Elements
Styling Basics
Text Styling (Color, Alignment, Decoration)
Box Model (Margin, Padding, Border, Width, Height)
Background Styling
Background Color
Background Images
Composite Background Properties
1. Introduction to CSS
What is CSS?
Cascading Style Sheets (CSS) is a stylesheet language used to control the visual presentation of web pages. It allows developers to define styles, layouts, colors, and animations, ensuring a consistent and appealing design across devices.
Key Features:
Separation of content (HTML) and design (CSS).
Ability to reuse styles across multiple pages.
Flexibility to create responsive and interactive designs.
Importance of CSS in Web Development
CSS transforms plain HTML documents into visually rich and user-friendly web pages. Some of the primary benefits include:
Enhanced readability and usability.
Support for responsive web design.
Simplified maintenance through reusable styles.
Overview of CSS Integration Methods
CSS can be linked to HTML in three ways, each with its use cases. The choice of method depends on the project scale and requirements.
2. Three Ways to Link CSS
Inline CSS
Inline CSS involves applying styles directly to HTML elements using the style
attribute. It has the highest priority, making it useful for quick changes but less maintainable for larger projects.
Example:
<body style="background-color: #808080;">
Advantages:
- Quick and easy for minor modifications.
Disadvantages:
Difficult to maintain as styles are embedded in the HTML structure.
Limited reusability.
Internal CSS
Internal CSS is written within the <style>
tag in the <head>
section of an HTML document. This method is ideal for single-page designs or isolated styling needs.
Example:
<style>
body {
background-color: #de6690;
}
</style>
Advantages:
Keeps styles separate from content.
Suitable for single-page applications.
Disadvantages:
- Not reusable across multiple pages.
External CSS
External CSS involves writing styles in a separate file and linking it to the HTML document. This is the most scalable method and a standard practice for large projects.
Example:
<link rel="stylesheet" href="./Style.css">
Advantages:
Reusability across multiple pages.
Easier maintenance and consistency.
Disadvantages:
- Requires additional HTTP requests.
Priority of CSS Methods
When combining methods, CSS follows a hierarchy of precedence:
Inline CSS (highest priority).
Internal CSS.
External CSS (lowest priority).
3. How CSS Works
How CSS Works
CSS (Cascading Style Sheets) operates by applying styles to HTML elements based on defined rules. These rules consist of selectors and declarations. To fully understand how CSS works, let’s break it down into its fundamental components and workflow.
Key Components of CSS
Selectors:
A selector determines which HTML element(s) the styles will apply to.Examples:
Universal selector (
*
): Applies to all elements.Type selector (
h1
,p
): Targets specific HTML tags.Class selector (
.classname
): Styles elements with a specific class.ID selector (
#idname
): Styles a unique element by its ID.
Declarations:
A declaration specifies the styling rules to apply to the selected elements. It is written as a property-value pair.Example:
color: red;
Property: The characteristic to style (e.g.,
color
,background-color
,font-size
).Value: The setting for that property (e.g.,
red
,#ff0000
,16px
).
Declaration Block:
Declarations are grouped inside curly braces{}
.
Example:h1 { color: red; font-size: 24px; }
Rule:
A complete CSS rule consists of a selector and a declaration block.
Example:p { color: blue; text-align: center; }
Understanding the Cascading Nature
The "cascading" in CSS refers to the way styles are applied based on a set of rules and priorities. CSS processes styles in the following order of precedence:
Inline CSS (highest priority):
Defined directly within an HTML element’sstyle
attribute.
Example:<p style="color: green;">This is inline CSS.</p>
Internal CSS:
Written inside the<style>
tag within the<head>
of the HTML document.
Example:<style> p { color: blue; } </style>
External CSS (lowest priority):
Defined in an external file linked to the HTML document using the<link>
tag.
Example:<link rel="stylesheet" href="styles.css">
When multiple styles are applied to the same element, the style with the highest precedence takes effect. For example, if both inline and external styles are applied to a paragraph, the inline style will override the external style.
Example: Combining CSS Methods
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./styles.css">
<style>
body {
background-color: #de6690; /* Internal CSS */
}
</style>
<title>CSS Priorities</title>
</head>
<body style="background-color: #808080;"> <!-- Inline CSS -->
<h1>Hello, CSS!</h1>
<p>This is a demonstration of CSS priorities.</p>
</body>
</html>
In this example:
The body element has three conflicting background colors defined:
Inline CSS:
background-color: #808080;
Internal CSS:
background-color: #de6690;
External CSS: (from
styles.css
, e.g.,background-color: #ffffff;
).
Result: The background color of the body will be gray (#808080
), as the inline style has the highest priority.
Selector Types in Detail
Universal Selector:
The universal selector applies styles to all elements in the document.
Example:* { margin: 0; padding: 0; }
Individual Selector:
Targets specific HTML tags by their names.
Example:h1 { font-size: 32px; color: blue; }
Class Selector:
Targets elements with a specificclass
attribute. Classes can be applied to multiple elements.
Example:.highlight { background-color: yellow; }
ID Selector:
Targets a single element with a specificid
attribute. IDs must be unique.
Example:#header { font-size: 24px; font-weight: bold; }
How Declarations Work
Declarations consist of properties and values. The browser interprets these declarations and applies the styles accordingly.
Example:
p {
color: rgb(248, 248, 11); /* Property: color, Value: rgb(248, 248, 11) */
text-align: center; /* Property: text-align, Value: center */
}
In the example:
color
changes the text color.text-align
centers the text within its container.
Common Properties and Their Uses:
Property | Description | Example |
color | Sets the text color | color: red; |
background-color | Sets the background color | background-color: #fff; |
margin | Sets the outer spacing of an element | margin: 10px; |
padding | Sets the inner spacing of an element | padding: 5px; |
font-size | Sets the size of the text | font-size: 16px; |
border | Adds a border around the element | border: 1px solid #000; |
Visual Representation: How CSS Works
Conclusion
Understanding how CSS works is fundamental to creating visually appealing and functional web designs. By mastering selectors, declarations, and the cascading priority, you can control the appearance of web pages effectively. Next, we will dive deeper into CSS Selectors and explore their applications with practical examples.
4. CSS Selectors Explained
CSS Selectors
CSS Selectors are the backbone of CSS, allowing you to target specific elements in an HTML document and apply styles to them. They determine which HTML elements the associated styles will affect. Selectors range from simple element types to complex patterns for advanced styling.
Categories of CSS Selectors
CSS Selectors are broadly categorized into the following:
Basic Selectors
Combinator Selectors
Pseudo-class Selectors
Pseudo-element Selectors
Attribute Selectors
Let’s explore each category in detail.
1. Basic Selectors
a. Universal Selector (*
)
The universal selector targets all elements on the page.
* {
margin: 0;
padding: 0;
}
b. Type Selector
Targets specific HTML elements by their tag names.
p {
color: blue;
}
c. Class Selector (.classname
)
Targets all elements with a specific class attribute.
.button {
background-color: #4CAF50;
color: white;
}
d. ID Selector (#idname
)
Targets a single unique element with a specific ID.
#header {
font-size: 24px;
text-align: center;
}
e. Grouping Selector
Applies the same styles to multiple selectors, separated by commas.
h1, h2, h3 {
color: green;
font-family: Arial, sans-serif;
}
CSS Selectors: A Deep Dive
Selectors are one of the most critical aspects of CSS. They help target specific elements in an HTML document for styling. Let's explore individual selectors, IDs, classes, and the background
property step by step.
1. Individual Selectors
An individual selector targets specific HTML elements directly. In this example, <h1>
and <p>
are individual selectors because they apply styles to those specific tags.
CSS Code:
p {
color: rgb(248, 248, 11); /* Yellow text */
}
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./Style.css">
<title>HTML and CSS Revision</title>
</head>
<body>
<h1>Hello Rohit</h1> <!-- Individual selector: h1 -->
<p>Lorem ipsum dolor sit amet consectetur adipisicing.</p> <!-- Individual selector: p -->
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ex, eaque.</p> <!-- Same selector as the first p -->
</body>
</html>
Explanation:
<h1>
is styled independently when a specific selector likeh1
is used in CSS.Both
<p>
elements use the same CSS rules because they share the same tag and therefore the same selector.
2. ID and Class Selectors
ID Selectors
IDs are unique; they can only be assigned to one element per page.
Syntax: Use
#
followed by the ID name in CSS.
Class Selectors
Classes are reusable; you can assign the same class to multiple elements.
Syntax: Use
.
followed by the class name in CSS.
CSS Code:
/* Styling an ID */
#para {
background-color: #39056c; /* Purple background */
}
/* Styling a class */
.head {
color: blanchedalmond; /* Pale yellow text */
}
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./Style.css">
<title>HTML and CSS Revision</title>
</head>
<body>
<h1 id="para">Hello Rohit</h1> <!-- Styled using ID -->
<p class="head">Lorem ipsum dolor sit amet consectetur adipisicing.</p> <!-- Styled using class -->
<p class="head">Lorem ipsum dolor sit amet consectetur adipisicing elit. Ex, eaque.</p> <!-- Same class applied -->
</body>
</html>
Explanation:
ID Selector: Targets only the
<h1>
element withid="para"
. It gives a purple background to the heading.Class Selector: Targets all elements with
class="head"
. Both<p>
elements share the same pale-yellow text style.
3. Applying Background as an Image
CSS allows setting an element's background as an image with the background
property. Instead of defining individual properties, you can combine all related properties into a shorthand background
property.
CSS Code:
body {
background: url('background.jpg') no-repeat center center;
background-size: cover; /* Ensures the image covers the entire area */
}
Explanation of Shorthand:
background-color
: Sets the background color.background-image
: Sets the image URL.background-repeat
: Determines if the image should repeat (e.g.,repeat
,no-repeat
).background-position
: Positions the image (e.g.,center center
,top left
).
HTML Code:
Practical Examples
2. Styling Form Elements
input:focus {
border: 2px solid blue;
outline: none;
}
button:hover {
background-color: lightgreen;
}
Best Practices for Using Selectors
Keep it Specific:
Overly generic selectors like*
can lead to performance issues. Use specific selectors whenever possible.Avoid Overusing IDs:
IDs are highly specific and should be used sparingly. Prefer classes for reusable styles.Minimize Combinator Depth:
Deeply nested combinators (e.g.,div ul li span
) are harder to maintain and can reduce performance.Leverage Grouping:
Combine selectors for shared styles to avoid redundancy.h1, h2, h3 { margin: 0; font-family: sans-serif; }
Conclusion
CSS selectors are essential tools for targeting elements and applying styles effectively. By mastering the variety of selectors, including pseudo-classes, pseudo-elements, and attribute selectors, you can achieve highly specific and dynamic designs. The proper use of selectors not only ensures better styling but also maintains code clarity and performance.
6. Styling Basics
CSS: Margin, Padding, Height, Width, and Text Properties
CSS plays a vital role in defining the layout and appearance of elements. Let's break down these essential concepts: Margin, Padding, Height and Width, and Text Properties, with examples.
1. Margin
Margin is the space outside the border of an element. It creates separation between elements.
Example: Margins
.para {
border: 2px double rgb(40, 3, 134); /* Visualize the margin effect */
margin: 10px 15px 20px 25px; /* Top, Right, Bottom, Left */
height: 500px;
width: 500px;
background-color: #8f0202;
}
Top margin: 10px
Right margin: 15px
Bottom margin: 20px
Left margin: 25px
The margin adjusts the spacing around the element relative to other elements or the container.
2. Padding
Padding is the space inside the border of an element, between the content and the border.
Example: Padding
.para {
border: 2px double rgb(40, 3, 134); /* Visualize the padding effect */
padding: 10px 15px 20px 25px; /* Top, Right, Bottom, Left */
height: 500px;
width: 500px;
background-color: #8f0202;
}
Top padding: 10px
Right padding: 15px
Bottom padding: 20px
Left padding: 25px
The padding adjusts the spacing inside the element, pushing content away from the edges.
3. Height and Width
Height and Width specify the dimensions of an element. They apply only to the content area, excluding margins and borders unless the box-sizing
property is used.
Example: Height and Width
.para {
border: 2px double rgb(40, 3, 134);
height: 500px; /* Vertical size */
width: 500px; /* Horizontal size */
background-color: #8f0202;
}
This example creates a square box of 500px × 500px.
Tip: Adding margins, borders, or paddings will affect the total area unless you use
box-sizing: border-box;
, which includes these in the dimensions.
4. Text Properties
CSS text properties help style and position text within elements.
Example: Text Alignment
.para {
height: 500px;
width: 500px;
background-color: #8f0202;
color: rgb(184, 112, 18);
text-align: center; /* Aligns text horizontally */
}
Other text-align
values:
Left (
text-align: left;
): Aligns text to the left.Right (
text-align: right;
): Aligns text to the right.Justify (
text-align: justify;
): Stretches text to align both the left and right edges.
Example: Text Decoration
.para {
text-decoration-line: underline; /* Adds an underline */
text-decoration-line: overline; /* Adds a line above */
text-decoration-line: line-through; /* Strikes through text */
text-decoration-line: none; /* Removes decorations */
}
Combined Example
.para {
border: 2px double rgb(40, 3, 134);
height: 500px;
width: 500px;
background-color: #8f0202;
color: rgb(184, 112, 18);
text-align: center;
text-decoration-line: underline;
margin: 10px;
padding: 20px;
}
This example showcases:
A border to visualize margins and paddings.
Height and width to define the element's size.
Text alignment (
center
) and decoration (underline
).
Full Code
Key Points to Remember
Margin affects the space outside the element.
Padding adjusts the space inside the element.
Height and Width control the content dimensions of an element.
Text Properties like alignment and decoration enhance typography styling.
By mastering these properties, you can precisely control the layout and appearance of your webpage elements. Next, let's dive into CSS Borders and Backgrounds for more visual customization.
Box Model
Understanding the box model is crucial for layout design. It includes:
Margin: Space outside the element.
Padding: Space inside the element.
Border: Boundary around the content.
Stay tuned for the next chapter, where we’ll dive into advanced layout techniques!
Related Posts in My Series:
Chapter 1:Mastering the Web: A Journey Through HTML and Beyond
Other Series:
Connect with Me
Stay updated with my latest posts and projects by following me on social media:
LinkedIn: Connect with me for professional updates and insights.
GitHub: Explore my repository and contributions to various projects.
LeetCode: Check out my coding practice and challenges.
Your feedback and engagement are invaluable. Feel free to reach out with questions, comments, or suggestions. Happy coding!
Rohit Gawande
Full Stack Java Developer | Blogger | Coding Enthusiast
Subscribe to my newsletter
Read articles from Rohit Gawande directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Rohit Gawande
Rohit Gawande
🚀 Tech Enthusiast | Full Stack Developer | System Design Explorer 💻 Passionate About Building Scalable Solutions and Sharing Knowledge Hi, I’m Rohit Gawande! 👋I am a Full Stack Java Developer with a deep interest in System Design, Data Structures & Algorithms, and building modern web applications. My goal is to empower developers with practical knowledge, best practices, and insights from real-world experiences. What I’m Currently Doing 🔹 Writing an in-depth System Design Series to help developers master complex design concepts.🔹 Sharing insights and projects from my journey in Full Stack Java Development, DSA in Java (Alpha Plus Course), and Full Stack Web Development.🔹 Exploring advanced Java concepts and modern web technologies. What You Can Expect Here ✨ Detailed technical blogs with examples, diagrams, and real-world use cases.✨ Practical guides on Java, System Design, and Full Stack Development.✨ Community-driven discussions to learn and grow together. Let’s Connect! 🌐 GitHub – Explore my projects and contributions.💼 LinkedIn – Connect for opportunities and collaborations.🏆 LeetCode – Check out my problem-solving journey. 💡 "Learning is a journey, not a destination. Let’s grow together!" Feel free to customize or add more based on your preferences! 😊