Selector - Specifying Targets for Styling
CSS selectors
allow you to select HTML elements in various ways as shown below.
Universal Selector
Use the *
symbol to select all HTML elements.
CSS
* {
color: blue; /* Sets the text color for all HTML elements to blue */
}
Element Selector
Select HTML elements by their tag name.
CSS
p {
font-size: 16px; /* Sets the font size of all <p> tags to 16px */
}
Class Selector
Select HTML elements by using the class name in the .class
format.
CSS
.highlight {
background-color: yellow; /* Sets the background color to yellow for elements with the class "highlight" */
}
ID Selector
Select HTML elements by using the ID in the #id
format.
CSS
#header {
font-weight: bold; /* Sets text to bold for elements with the ID "header" */
}
Descendant Selector
Select nested elements within a parent element.
CSS
ul li {
list-style: circle; /* Selects <li> tags within a <ul> and sets their list style to circle */
}
HTML & CSS Usage Example
Below is an example of using HTML and CSS together.
HTML
<body>
<p class="my-class">This HTML element uses the <code>p</code> tag and has the class <code>my-class</code>.</p>
<h1 id="my-id">This HTML element uses the <code>h1</code> tag and has the ID <code>my-id</code>.</p>
</body>
CSS
p {
color: red;
}
.my-class {
background-color: blue;
}
#my-id {
font-size: 20px;
}
This CSS will render as follows:
(Red text) This HTML element uses the p
tag and has the class my-class
.
(Blue background) This HTML element uses the h1
tag and has the ID my-id
.
In the next session, we will explore advanced selector compositions.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.