CSS Selectors
What is CSS selectors?
CSS selectors allow you to select and manipulate HTML elements.
CSS selectors are used to “find” (or select) HTML elements based on their id, class, type, attribute, and more.
There are many types of selectors. We will describe here each of them with example.
Element Selectors:
For example if we talk about Element selector that means it selects elements based on the element name.
Suppose that I have to select all <p> elements on a page like this: (all <p> elements will be center-aligned, with a red text color)
p { text-align: center; color: red; }
Let’s have a look on Complete example:
<!DOCTYPE html>
<html>
<head>
<style>
p {
text-align: center;
color: red;
}
</style>
</head>
<body>
<p>Hi, This is a test example. Here you will see that paragraph will be affected by the style.</p>
<p id=”para1″>Here Also</p>
<p>Again Here </p>
</body>
</html>
ID selectors:
The id selector uses the id attribute of an HTML element to select a specific element.
An id should be unique within a page, so the id selector is used if you want to select a single, unique element.
To select an element with a specific id, write a hash character, followed by the id of the element.
The style rule below will be applied to the HTML element with id=”para1″:
Let’s have an example:
#para1 {
text-align: center;
color: red;
}
Complete Example:
<!DOCTYPE html>
<html>
<head>
<style>
#para1 {
text-align: center;
color: red;
}
</style>
</head>
<body>
<p id=”para1″>Here id selector works</p>
<p>But in this paragraph, id selector does not work</p>
</body>
</html>
The class Selector:
The class selector selects elements with a specific class attribute.
To select elements with a specific class, write a period character, followed by the name of the class:
Let’s have an example below, all HTML elements with will be center-aligned:
.center {
text-align: center;
color: red;
}
Complete Example:
<!DOCTYPE html>
<html>
<head>
<style>
.center {
text-align: center;
color: red;
}
</style>
</head>
<body>
<h1 class=”center”>Red and center-aligned heading</h1>
<p class=”center”>Red and center-aligned paragraph.</p>
</body>
</html>
Grouping Selectors:
If you have elements with the same style definitions, like td, tr, th or as below:
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}
p {
text-align: center;
color: red;
}
you can group the selectors, to minimize the code.
To group selectors, separate each selector with a comma.
Let’s have a complete example below. Here, we have grouped the selectors from the code above:
<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, p {
text-align: center;
color: red;
}
</style>
</head>
<body>
<h1>Hi, This is my first heading</h1>
<h2>Its smaller one</h2>
<p>Its paragraph.</p>
</body>
</html>