Target the right element is a must-know. Here's a recap of the available options. Examples are for the following structure:
<h2>Some title</h2>
<p>A paragraph</p>
<div>
<p>I am child of div</p>
<p>The guy up there is my bro.</p>
<section>
<p>Lonely paragraph</p>
</section>
<p>Third brother.</p>
</div>
<p>Out of div</p>
<p>Same</p>
As always, a demo is available on CodePen.
Separate the elements with a ,.
h2, section {
font-weight: bolder;
color: navy;
}
Separate the parent element from the descendant element with a space.
div p {
text-decoration: underline;
}
Separate the parent element from the child element with a >.
body > p {
font-family: monospace;
}
Separate the first bro element from the second with a +.
div + p {
text-align: center;
}
Separate the first bro element from the other ones ~.
div ~ p {
width: 20%;
padding: 0.5em;
border: 0.25em solid indianred;
}
A full list can be found on MDN Web Docs.
Use a pseudo class after the element's name you want to target:
p:first-child {
letter-spacing: 0.25em;
}
p:nth-of-type(3n) {
color: blue;
}
Locate a starting point then create inline elements or specific decoration. For instance:
h2::before {
content: "♥ ";
}
h2::selection {
background-color: gold;
}
There's no attribute in the demo page. See attribute selectors