CSS selectors are patterns that define which HTML elements will be affected by a given set of CSS rules. Selectors can be based on various criteria, including element names, classes, IDs, attributes, and more. Here are some common types of selectors:
p {
color: blue;
}
.highlight {
background-color: yellow;
}
#header {
font-size: 24px;
}
input[type="text"] {
border: 1px solid #ccc;
}
Descendant Selector: Selects an element that is a descendant of another element.
In this example, all li
under ul
will have square bullets
ul li {
list-style: square;
}
Child Selector: Selects an element that is a direct child of another element.
In this example, only the ul
directly under nav
tag will have margin: 0
nav > ul {
margin: 0;
}
:hover
, :first-child
, ::before
, and ::after
.Specificity is a set of rules that determines which CSS rule takes precedence when multiple rules target the same element. Specificity is essential for resolving conflicts between CSS rules. The specificity of a selector is calculated based on the following factors:
style
attribute have the highest specificity.Specificity is calculated using a four-part notation, where each part represents the number of occurrences of the corresponding selector type. For example:
0,0,1,0
represents one class selector.0,1,0,0
represents one ID selector.1,0,0,0
represents one element selector.