Skip to main content
Practice

Selector: Specifying the Elements to Style

CSS selectors enable you to select HTML elements in various ways as shown below.


Universal Selector: Selects all HTML elements using the * symbol

CSS
* {
color: blue; /* Sets the text color of all HTML elements to blue */
}

Element Selector: Selects HTML elements based on the tag name

CSS
p {
font-size: 16px; /* Sets the font size of all p tags to 16px */
}

Class Selector: Selects HTML elements based on the class name using the .class format

CSS
.highlight {
background-color: yellow; /* Sets the background color of elements with the highlight class to yellow */
}

ID Selector: Selects HTML elements based on the ID using the #id format

CSS
#header {
font-weight: bold; /* Sets the font weight of the element with the header ID to bold */
}

Descendant Selector: Selects elements nested within another element

CSS
ul li {
list-style: circle; /* Sets the list style of li tags inside ul to a circle */
}

HTML & CSS Example

Below is an example of using HTML and CSS together.

HTML
<body>
<p class="my-class">This HTML element uses the `p` tag and has the `my-class` class.</p>
<h1 id="my-id">This HTML element uses the `h1` tag and has the `my-id` ID.</h1>
</body>
CSS
p {
color: red;
}

.my-class {
background-color: blue;
}

#my-id {
font-size: 20px;
}

The above CSS results in:

(Red text) This HTML element uses the p tag and has the my-class class. (Blue background) This HTML element uses the h1 tag and has the my-id ID.

In the next lesson, we will explore more advanced selector configurations.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.