Compound Selectors
In CSS, compound selectors are used to select elements based on multiple conditions. Compound selectors are created by combining two or more simple selectors. Compound selectors allow you to target elements based on multiple conditions, such as the presence of a class and an attribute, or the type of an element and its state.
Syntaxβ
The syntax for compound selectors is as follows:
selector1.selector2 {
/* CSS properties */
}
selector1
: The first simple selector.selector2
: The second simple selector.CSS properties
: The CSS properties to be applied to the compound selector..
: The.
character represents the class selector.- The
.
character is used to select elements based on the presence of a class. - Compound selectors are created by combining two or more simple selectors.
- Compound selectors allow you to target elements based on multiple conditions.
Exampleβ
In the following example, the compound selector is used to select all <a>
elements with the class button
:
a.button {
color: blue;
text-decoration: none;
}
In the HTML code below, the CSS rule will apply the color: blue
and text-decoration: none
properties to all <a>
elements with the class button
:
<a href="#" class="button">Click Here</a>
- Compound selectors are created by combining two or more simple selectors.
- Compound selectors allow you to target elements based on multiple conditions.
- Compound selectors are useful for styling elements that meet specific criteria.
- Compound selectors can be used to target elements based on their type, class, ID, attribute, or state.
- Compound selectors are more specific than simple selectors and less specific than complex selectors.
Example: Using Compound Selectorsβ
In the following example, the compound selector is used to select all <a>
elements with the class button
:
- index.html
- index.css
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<a href="#" class="button">Click Here</a>
</body>
</html>
a.button {
color: blue;
text-decoration: none;
}
Now, you can see the output of the above code in the Browser Window like this:
In this example, the compound selector a.button
is used to select all <a>
elements with the class button
and apply the color: blue
and text-decoration: none
properties to them. The <a>
element in the HTML code has the class button
, so the CSS rule is applied to it.
Summaryβ
Compound selectors are used to select elements based on multiple conditions. They are created by combining two or more simple selectors. Compound selectors allow you to target elements based on specific criteria, such as the presence of a class or an attribute. Compound selectors are more specific than simple selectors and less specific than complex selectors. They are useful for styling elements that meet specific criteria.