Selectors: Targeting Elements for Styling
CSS Selectors
allow you to select HTML elements in various ways as shown below.
Universal Selector: Uses the *
symbol to select all HTML elements
* {
color: blue; /* Sets the text color of all HTML elements to blue */
}
Element Selector: Uses the HTML tag name to select HTML elements with that tag
p {
font-size: 16px; /* Sets the font size of all p tags to 16px */
}
Class Selector: Uses the .class
format to select HTML elements with a specific class
.highlight {
background-color: yellow; /* Sets the background color of elements with the 'highlight' class to yellow */
}
ID Selector: Uses the #id
format to select HTML elements with a specific ID
#header {
font-weight: bold; /* Sets the font weight of the element with the ID 'header' to bold */
}
Descendant Selector: Selects elements nested within other elements
ul li {
list-style: circle; /* Sets the list style to circle for li tags within ul tags */
}
HTML & CSS Example
Here's an example of using HTML and CSS together.
<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>
p {
color: red;
}
.my-class {
background-color: blue;
}
#my-id {
font-size: 20px;
}
This CSS will render the following:
(The text in red) This HTML element uses the p
tag and has the my-class
class.
(The text with blue background) This HTML element uses the h1
tag and has the my-id
ID.
In the next lesson, we will explore advanced selector techniques.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.