A Beginner's Guide to CSS: Mastering Cascading Style Sheets


CSS and its Syntax:
CSS stands for Cascading Style Sheets.
It controls the visual presentation (style, layout, color, fonts, spacing, etc.) of HTML elements.
Why Use CSS?
Without CSS:
<h1>Hello</h1>
With CSS:
<h1 style="color: blue; font-family: Arial;">Hello</h1>
๐ 3 Ways to Add CSS
Method | How to Use | Example |
Inline | Inside the HTML tag | <p style="color:red;">Text</p> |
Internal | Inside a <style> tag in <head> | <style>p { color: red; }</style> |
External โ | Linked .css file | <link rel="stylesheet" href="styles.css"> |
CSS Syntax
selector {
property: value;
}
โ Example:
h1 {
color: blue;
font-size: 24px;
}
This means: make all <h1>
elements blue and 24px in size.
CSS Selectors
Selectors target which elements to style.
๐น 1. Universal Selector (*
)
Targets all elements.
* {
margin: 0;
padding: 0;
}
๐น 2. Element Selector
Targets a specific HTML tag.
p {
color: green;
}
๐น 3. Class Selector (.
)
Targets elements with a specific class.
<p class="highlight">Hello</p>
.highlight {
background-color: yellow;
}
๐น 4. ID Selector (#
)
Targets an element with a unique ID.
<h1 id="main-title">Welcome</h1>
#main-title {
font-size: 30px;
}
๐น 5. Group Selector
Style multiple elements at once.
h1, h2, p {
font-family: Arial;
}
๐น 6. Descendant Selector
Select elements inside other elements.
article p {
color: gray;
}
Applies to all <p>
inside <article>
.
๐น 7. Child Selector (>
)
Selects direct children only.
ul > li {
list-style-type: square;
}
๐น 8. Adjacent Sibling Selector (+
)
Selects the next sibling only.
h2 + p {
color: purple;
}
๐น 9. Attribute Selector
Targets elements by attributes:
input[type="text"] {
border: 1px solid gray;
}
๐น 10. Pseudo-class Selectors
Used for states or dynamic interaction.
Selector | Meaning |
:hover | When mouse is over element |
:focus | When an input is focused |
:first-child | First child of a parent |
:last-child | Last child |
button:hover {
background-color: red;
}
๐น 11. Pseudo-elements
Target parts of an element.
p::first-line {
font-weight: bold;
}
Specificity (Which Style Wins?)
Selector Type | Specificity Score |
Element (p ) | 1 |
Class (.x ) | 10 |
ID (#id ) | 100 |
Inline Style | 1000 |
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: sans-serif;
}
h1 {
color: blue;
}
.highlight {
background-color: yellow;
}
#intro {
font-style: italic;
}
</style>
</head>
<body>
<h1 id="intro">Welcome!</h1>
<p class="highlight">This is a highlighted paragraph.</p>
</body>
</html>
Subscribe to my newsletter
Read articles from koustav moitra directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
