Since both of the following have the same effect:
.class {
cursor:pointer;
}
.class:hover {
cursor:pointer;
}
Regarding best practices, which one should you use and why?
The two selectors are for distinctly separate purposes, despite the fact that- at least in practice they appear to accomplish the same thing.
I would tend to say it would be best practice to define the hover state using :hover
(at least on non-touchscreen devices, see below), because:
It makes finding and understanding your styling more apparent in larger blocks of CSS
It utilizes a specifically designated selector (which may be extended in the spec at a later date, what would then happen to your functionality?)
If you later add to the default styling for .class
your states are clearly separated appropriately
What happens if you hand over responsibility of your CSS to another individual? Having :hover
specific functionality defined under the correct selector makes understanding code a heck of a lot easier.
If you have more complex CSS its likely you'll be using :hover
elsewhere, so should use it for the purposes of consistency
The two selectors represent the same element but in different states, semantically you should use :hover
But hang on a minute.. you may notice that if you set the cursor style for an a
element to default
then the usual hand icon wont appear on hover...this indicates that there is baked-in prior evidence for not specifically styling :hover
states (see this in action here)
In summary, there is no game breaking reason not to use simply .class
in some circumstances- it certainly uses less bytes and if you have a fairly simple setup then only under development by you...then why not, but be wary it is probably best avoided if you want to adhere to the strict rules and better support ongoing development.
In addition..lets not forget touchscreen devices MDN makes an important point here
on touch screens :hover is problematic or impossible. The :hover pseudo-class never matches, or matches for a short moment after touching an element. As touchscreen devices are very common, it is important for web developer not to have content accessible only when hovering over it, as this content would be hidden for users of such devices.
As such depending on your requirement, it may not be best to use :hover
as if you have it in your CSS for a touch screen device it may bake in reliance on unsupported or flakey functionality.
IE6 and lower only recognises the :hover
pseudo class on a
tags. :hover
on a div
or other tag will not be interpreted by those browsers.
If compatibility is a consideration, use the :hover
else I believe there is no difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With