CSS Syntax and Selectors
✅ CSS Syntax
CSS (Cascading Style Sheets) is used
to apply styles to HTML elements. The basic syntax of a CSS rule is:
selector
{
property: value;
}
Example:
p
{
color: blue;
font-size: 16px;
}
Explanation:
- p → Selector: targets all
<p>
elements.
- color and font-size
→ Properties.
- blue and 16px → Values.
✅
CSS Selectors
Selectors define which HTML
elements the CSS rules apply to. Here are the most common types:
🔹 1. Universal Selector (*)
Applies to all elements on
the page.
*
{
margin: 0;
padding: 0;
}
🔹 2. Element Selector
Targets HTML elements directly.
css
CopyEdit
h1
{
text-align: center;
}
🔹 3. Class Selector (.classname)
Targets elements with a specific
class.
<p
class="intro">Welcome</p>
.intro
{
font-style: italic;
}
🔹 4. ID Selector (#idname)
Targets a specific element with a
unique ID.
<div
id="main-banner">Hello</div>
#main-banner
{
background-color: lightblue;
}
🔹 5. Group Selector
Apply same styles to multiple
selectors.
h1,
h2, h3 {
font-family: Arial;
}
🔹 6. Descendant Selector
Targets elements nested inside other
elements.
article
p {
line-height: 1.5;
}
🔹 7. Child Selector (>)
Only applies to direct
children.
ul
> li {
list-style-type: square;
}
🔹 8. Attribute Selector
Targets elements with specific
attributes.
input[type="text"]
{
border: 1px solid gray;
}
🔹 9. Pseudo-classes
Used for styling elements in a
specific state.
a:hover
{
color: red;
}
Common pseudo-classes: :hover, :active, :focus,
:first-child, :last-child, :nth-child(n)
🔹 10. Pseudo-elements
Style specific parts of an element.
p::first-letter
{
font-size: 200%;
}