CSS Selectors


🔹 What are CSS Selectors?

CSS Selectors are used to target HTML elements you want to style.
They tell the browser which elements the CSS rule applies to.


🔸 Basic Selectors

Selector Description Example
* Universal selector – targets all elements * {margin: 0;}
element Targets all elements of a type p {color: red;}
.class Targets all elements with a specific class .note {font-size: 16px;}
#id Targets a specific element by ID #header {color: blue;}
element1, element2 Targets multiple elements h1, p {margin: 10px;}

🔸 Grouping Selectors

Use a comma , to apply the same style to multiple elements.

h1, h2, p {
  color: navy;
}

🔸 Class Selector (.classname)

<p class="intro">This is a paragraph.</p>
.intro {
  color: green;
}

🔸 ID Selector (#idname)

<h1 id="main-title">Welcome</h1>
#main-title {
  font-size: 24px;
}

🔸 Universal Selector (*)

* {
  box-sizing: border-box;
}

🔸 Group Selector

h1, h2, p {
  font-family: Arial;
}

Practice Questions

Q1. Target all <p> elements and change their font size to 16px.

Q2. Style all <h1> and <h2> elements to have blue text color using a group selector.

Q3. Create a class .highlight and apply a yellow background color.

Q4. Write a rule to target an element with ID #banner and make its text bold.

Q5. Use the universal selector to remove all margins.

Q6. Create a .button class that changes text color to white.

Q7. Write a CSS rule to apply a font family of Arial to all <div> elements.

Q8. Combine a group selector to style <ul> and <ol> with the same padding.

Q9. Write a class .card to set the border to 1px solid gray.

Q10. Write a rule that applies the same font size to <h1>, <h2>, and <p> elements.


CSS Selectors Quiz

Q1: Which CSS selector targets all elements?

A. #
B. .
C. *
D. all

Q2: What does .box target in CSS?

A. Element with ID “box”
B. All <box> tags
C. Elements with class “box”
D. Box-shadow property

Q3: What does #header target?

A. All header tags
B. The first header
C. Element with class “header”
D. Element with ID “header”

Q4: How do you apply styles to both <h1> and <p> tags?

A. h1 + p {}
B. h1, p {}
C. h1 p {}
D. h1 .p {}

Q5: Which is a valid class selector?

A. class=menu
B. .menu
C. menu.class
D. #menu

Q6: Which is a valid ID selector?

A. .main
B. id.main
C. #main
D. main#

Q7: What is the correct syntax for the universal selector?

A. * {}
B. all {}
C. % {}
D. @ {}

Q8: Which selector is used to group multiple elements?

A. .
B. #
C. *
D. ,

Q9: How would you style all <h2> elements with a class of “highlight”?

A. h2.highlight {}
B. .h2.highlight {}
C. #highlight h2 {}
D. h2#highlight {}

Q10: Which CSS selector selects all <div> elements with class “card”?

A. #card div
B. div.card
C. .div.card
D. card.div

Go Back Top