Combinators
Combinators are a special type of selectors that are used to combine other selectors in a way that gives them a useful relationship to each other and the location of content in the document. There are four types of combinators:
descendant (space)
child (
>
)adjacent (
+
)sibling (
~
)
Descendant
The descendant combinator, which is represented with space, selects all elements that are descendants of other selectors. The descendants are not limited to direct children.
This is the most commonly used combinator as it can affect the largest number of elements. Let's look at an example. If we had a navbar with a dropdown containing its own set of links then we would have anchor tags that are not direct children of the navbar.
Even so, it would be possible to style all of the links the same by using the descendant combinator.
If we wanted to select and style all of the anchor tags, we could use the descendant combinator.
Notice how both main navbar links and the dropdown-content links were styled. That is because even thought these links do not share the same parent element, they are still descendants of the navbar.
Child
The child combinator, which is represented as a >
, is to select only those elements that are direct children of the other selectors. This is different from the descendant combinator in that it will not affect any element beyond the direct children.
Let's return to our navbar example. But this time we are going to make an alteration. We have decided that while the background of the navbar is black, the dropdown content will be off-white.
This of course will make seeing the links very difficult to see. To fix this problem, let's target the main links using the child combinator instead. Then we can style the dropdown content links separately.
adjacent
The adjacent combinator, which is represented with a +
, will select the element that is the very next sibling to other selectors, if any exists. Let's see this in action. The following code will create a row of red boxes that turn blue when hovered over them.
But now, let's add an extra bit of code so that when you hover over a box, the next will turn orange, and we will use the adjacent combinator to do it.
Now, let's go back to our navbar. We made some additional changes to the navbar.
Last updated