A CSS selector is the first of a CSS rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them.
or "CSS Selectors are used to "find"(or select) the HTML elements you want to style.
- universal selector: Selects all elements of the DOM and make their margin and padding 0px.
* {
margin: 0;
padding: 0;
}
- Type selector: Selects all elements that have the given node name. Syntax ->
elementName
.a { text-decoration: none; }
Above, match any "a" tag and remove the underline or any text decoration.
- class selector: Selects all elements that have the given clasas attribute. Syntax ->
.className
..intro { color: blue; }
Above, .intro
will match any element that has a class of "intro" and change their text colour to blue.
- ID Selector: Selects an element based on the vlaue of its id attribute. There should be only one elemet with a given ID in a document. Syntax ->
#IdName
.#firstName { color: red; font-size: 20px; }
Above, #firstName
will match an element that has an id of "firstName" and apply these styles.
- Attribute selector: Selects all elements that have the given attribute. Syntax:
[attr][attr=value]
[title] {
font-weight: bold;
}
[attr=value]
: This represents elements with an attribute-name of attr whose value is exactly value.[attr~=value]
: Represents elements with an attribute-name of attr whose value is a whitespace-separated list of words, one of which is the exact value.[attr^=value]
: Represents elements with an attribute name of attr whose value is prefixed (preceded) by value.[attr$=value]
: Represents elements with an attribute name of attr whose value is suffixed (followed) by value.[attr*=value]
: Represents elements with an attribute-name of attr whose value contains at least one occurrence of value within the string.Selector list: The
,
is a grouping method, it selects all the matching nodes.
p, .start {
font-weight: bold;
}
Above, p.intro will match both <p>
and <div class="start">
elements.
- Child Combinator : The
>
combinator selects nodes that are direct children of the first element..intro > img { width: 50%; }
Above, it wil match all <img>
elements that are nested directly inside a <div class="intro">
element.
- General sibling combinator: The
~
combinator selects siblings. This means that the second element follows the first (though not necessarily immediately), and both share the same parent.
Example: p~span
will match all <span>
elements that follow a <p>
, immediately or not.
- Adjacent sibling combinator: The
+
combinator selects an adjacent sibling. This means that the second element directly follows the first, and both share the same parent.
Example : h2 + p
will match all <p>
elements that directly follow an <h2>
.
- Descendant combinator: The
Example : div span
will match all <span>
elements that are inside a <div>
element.
Hope you have enjoyed this post ๐