The case for using the Pseudo Class in CSS



Pseudo Classes are a crucial part of CSS. They allow developers to apply styles to elements under certain conditions. For example, if there is a <div> tag with 3 <p> tags inside of it, the :nth-child pseudo selector is able to specify which one of the <p> tags to apply a style to without needing a bunch of ids. Selecting elements without using ids is also really useful in dynamically generated websites, where a developer may want to style the first and last elements differently than the middle ones.

 

Join us in our newest publication:

Some pseudo classes are more than just a way to avoid an overload of ids, such as :hover. :hover allows developers to customize an element when the cursor is hovering on top of it. The :hover is a common part of customizing the look of standard links, which already have :hover events and may look ugly without customization.

 

Here is a demo of what can be achieved with pseudo classes. It will use a google font called Roboto, which can be added to most projects using the methods provided on https://www.google.com/fonts . This demo won’t contain a single id or class, yet it will still look nice and have basic functionality in the end with the power of pseudo classes. To start, create a <div> and 3 child <p> elements with <div> tags in between the <p> tags like this:

Screen Shot 2015-08-27 at 3.40.48 PM

 

 

It should look something like this:

 Screen Shot 2015-08-27 at 3.41.20 PM

 

 

Now the HTML is complete and we can move onto the CSS.

 

Start by styling the p tags with this:

 Screen Shot 2015-08-27 at 3.48.26 PM

 

 

Then try out the pseudo selectors :first-child, and :nth-child() like this:

 

Screen Shot 2015-08-27 at 3.53.19 PM

 

Now, it may seem odd that :nth-child() needed a 3 and 5 to select the correct elements versus 2 and 3. After all; it looks like the CSS is describing the third <p> tag inside of a <div>. It turns out that :nth-child() actually is describing the 3rd element of the parent element that happens to be a <p> tag. If we had typed “div p:nth-child(2)”, that would be interpreted as find a <p> that is the 2nd child of a <div>. It wouldn’t have found anything because the second child of our <div> isn’t a <p>.

 

Next, style the <div> tags inside of the parent <div> like this:

 Screen Shot 2015-08-27 at 4.18.55 PM

 

 

Which should produce this:

 Screen Shot 2015-08-27 at 4.19.54 PM

Doesn’t that look nice and customizeable? Now lets add some :hover functionality to really make it shine.

 

Its this easy to capture the hover event:

Screen Shot 2015-08-27 at 4.29.30 PM

 

Now when a <p> tag is hovered over it will turn black. :hover can make a site feel much more alive when used properly.

 

View and customize the result here: https://jsfiddle.net/MorganMeliment/zk4u5f8j/

 

Share and Enjoy !

0Shares
0 0