How do I select an element that has a certain class?
To select an HTML element with a certain class, use the class selector .
in CSS. Alternatively, use the JavaScript methods querySelector
(for a single element) or getElementsByClassName
(for all matching elements).
CSS:
JavaScript:
Understanding CSS Selectors
Styling an Element with a Class
To style a specific element (say, h2
) with a class, use tagName.className
format.
Styling Nested Elements
For nested elements, use parent.child
format. Here's how to color an h2
nested in .myClass
:
Mastering Selector Specificity
In CSS, specificity matters. More the classes, greater the weight.
Styling Strategies and Debugging
Cascading Styles: Ordering Rules
Remember, order matters in CSS styling. A rule at the bottom will override one at the top.
Debugging Styles
If your styles don't apply, review your HTML structure.
Is as good as a handshake with this CSS selector:
Color Coding Your Debugging
Why not color-code your debugging process? Use dev tools to track your styles.
Advanced Selector Techniques
Experimenting with Pseudo-Classes
Get exotic with pseudo-classes
like :first-child
or :nth-child
for ever more focused styling:
Deciphering Direct vs. Descendant Selectors
Know the difference between dealing with direct children (>
) vs. any descendant (space):
Was this article helpful?