CSS selectors are used to "find" (or select) HTML elements based on their element name, id, class, attribute, and more. Once elements are selected, you can then apply styles to them using CSS properties.
There are many types of CSS selectors, but the most basic are:
p {
color: red;
}
This will select all
<p>
elements in the HTML document and change their color to red.
id
attribute.#intro {
color: blue;
}
This will select the HTML element with
id="intro"
and change its color to blue.
class
attribute..myClass {
color: green;
}
This will select all HTML elements with
class="myClass"
and change their color to green.
CSS properties are used to style the elements selected by the CSS selectors. There are numerous CSS properties, but let's look at a few common ones:
p {
color: red;
}
p {
font-size: 20px;
}
p {
background-color: yellow;
}
Here are some practical examples:
Example 1
<!DOCTYPE html>
<html>
<head>
<style>
/* This is a CSS comment */
/* The color property changes the color of the text */
p {
color: red;
}
</style>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
This will change the color of all
<p>
elements to red.
Example 2
<!DOCTYPE html>
<html>
<head>
<style>
/* The # sign is used for id selectors */
/* The color property changes the color of the text */
#intro {
color: blue;
}
</style>
</head>
<body>
<p id="intro">This is an intro paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
This will change the color of the
<p>
element withid="intro"
to blue.
In this tutorial, you've learned about CSS selectors and properties. You've learned how to use element, id, and class selectors, and how to use properties such as color, font-size, and background-color.
For further learning, you can explore more about CSS selectors such as attribute selectors, pseudo-class selectors, and pseudo-elements selectors, and more CSS properties.
<div>
elements to purple.<p>
element with id="content"
to 25px.<h1>
elements with class="heading"
to orange.Solutions
div {
background-color: purple;
}
#content {
font-size: 25px;
}
.heading {
color: orange;
}