CHAINING CSS SELECTORS
Recently, I wrote a blog post about CSS: what it is, the way it is structured, tools that could be helpful, and some great resources. In this blog post, I will be focusing on chaining CSS selectors.
What is CSS selectors?
In CSS, selectors are patterns used to select the element(s) you want to style.
Basic Selectors:
- *{property:value;} /* will match all the elements of the document. */
- p{property:value;} /* will match any <p> element
- .classname{property:value;} /* for example,
.index
will match any element that has a class of "index". */ - #idname{property:value} /* for example,
#header
will match the element that has the ID "header". */ [attr]
[attr=value]
[attr~=value]
[attr|=value]
[attr^=value]
[attr$=value]
[attr*=value]
/* for example, [autoplay] will match all elements that have theautoplay
attribute set (to any value). */
Chaining selectors
There are so many ways to chain selectors. I will be focusing on ones that are most commonly used.
- .classname1.classname2
<div class="name1 name2">...</div><style>.name1.name2{property:value;} /* Selects all elements with both name1 and name2 set within its class attribute */</style>
- .classname1 .classname2
/* Be careful, if there is a space between them ( .classname1 .classname2 ), then CSS will select all elements with name2 that is a child of an element with name1 */<div class=”name1">
<div class=”name2">
…
</div>
</div><style>.name1 name2{property:value;} </style>
- element, element
<div> ... </div>
<p> ... </p><style>div, p{property:value;} /* Selects all <div> elements and all <p> elements */</style>
- element element
/* Be careful, if there is a space between them instead of comma ( element element ), then CSS will select all <p> elements inside <div> elements */<div>
<p>
…
</p>
</div><style>div p{property:value;} </style>
- element>element
<div>
<p> /* This will be selected */
…
</p>
</div><p> ... </p> /* This won't be selected */
<style>div>p{property:value;} /* Selects all <p> elements where the parent is a <div> element */</style>
- element+element
<div>
<p> /* This won't be selected */
...
</p>
</div><p> ... </p> /* This will be selected */
<p> ... </p> /* This won't be selected */<style>div+p{property:value;} /* Selects all <p> elements that are placed immediately after <div> elements */</style>
- [attribute^=value]
<a href="https..."></a><style>a[href^="https"]{property:value;} /* Selects every <a> element whose href attribute value begins with "https" */</style>
- [attribute$=value]
<a href="... .pdf"></a><style>a[href$=".pdf"]{property:value;} /*
Selects every <a> element whose href attribute value ends with ".pdf" */</style>
- ::before
<p> Paragraph 1 </p>
<p> Paragraph 2 </p><style>p::before{content: "Read this:"} /*
Inserts something before the content of each <p> element */</style>Output => Read this: Paragraph 1
Read this: Paragraph 2
You can find the full list here
Hope you find this blog post helpful. See you next time!
Resources: