Are you a visual learner? Do you resemble our bewildered friend above when trying to target elements for styling? If so, don’t worry, we’ll soon remedy that. If you’re just starting to learn basic selector syntax it can be hard to remember what does what. I’ve created this cat-based primer to guide you. Enjoy!
Target a Parent
Selecting a parent is as simple as using a class, id or element as your selector. Follow this with a declaration block and you’re in business. Here’s an example of the corresponding markup and styles, respectively.
<div class="parent">
<div class="child"></div>
<div class="child"></div>
</div>
.parent {
border: 10px solid cyan;
}
Here’s how it affects the DOM, with blue highlighting the targeted element:
Target a Child
Placing a space between selectors tells the browser to find the first
selector (the parent) and then go inside of it to find the second selector (its
child). In the following example we’re looking for any element within .parent
with the class of .child
.
<div class="parent">
<div class="child"></div>
<div class="child"></div>
</div>
.parent .child {
border: 10px solid cyan;
}
Here’s how it affects the DOM:
Target an Adjacent Sibling
An adjacent sibling is an element that resides next to, and on the same level of
the DOM as another. Targeting them is simple. In this case what we need to do is
join the selectors together with a +
. Check out the example below.
<div class="parent">
<div class="child"></div>
<div class="child"></div>
</div>
<div class="sibling">
<div class="child"></div>
</div>
.parent + .sibling {
border: 10px solid cyan;
}
Here’s how it affects the DOM:
Using Multiple Selectors
Sometimes you want to apply styles to multiple elements. So how does that work? The answer is quite simple. All one has to do is separate each selector with a comma. Here’s an example.
<div class="parent">
<div class="child"></div>
<div class="child"></div>
</div>
.parent,
.child {
border: 10px solid cyan;
}
Here’s how it affects the DOM:
Finish Strong
To learn even more about CSS selectors (though sadly with no cats), try CSS Diner, which will lead you from basic to complex selectors using delicious food.
Props
Thanks to all the cat lovers of Flickr. All cats herded under Creative Commons Attribution 2.0 Generic.
header-cat | parent-cat-one | kitten-one | kitten-two | full-cat-one | full-cat-two | goofy-cat | sibling-cat