How can I write 'a:hover' in inline CSS?
You cannot directly write a:hover
as inline CSS (e.g., using the style
attribute on an <a>
element). Inline CSS doesn’t allow pseudo-classes. To style :hover
, you must use either an external stylesheet, an internal <style>
block, or a JavaScript workaround.
Why Inline CSS Can’t Handle :hover
HTML’s style
attribute applies styles directly to that element, but pseudo-classes (like :hover
) need a selector that the browser evaluates in real time (i.e., when a user hovers). Inline CSS has no mechanism to express states such as hovering or focus.
Example of What Doesn’t Work
<a href="#" style=":hover { color: red; }">Hover over me</a> <!-- This is invalid and won't do anything. -->
Workarounds
1. Use an Internal or External Stylesheet
Instead of inline, define a rule in <style>
or an external .css
file:
Internal <style>
example:
<html> <head> <style> a:hover { color: red; } </style> </head> <body> <a href="#">Hover over me</a> </body> </html>
External CSS file example (styles.css
):
a:hover { color: red; }
<link rel="stylesheet" href="styles.css"> <a href="#">Hover over me</a>
- Pros: This is the usual, clean approach for styling.
- Cons: None—this is how CSS is designed to be used.
2. Use JavaScript (On Mouse Events)
If you absolutely must avoid a stylesheet, you could emulate a hover effect with JavaScript event handlers like onmouseover
and onmouseout
:
<a href="#" onmouseover="this.style.color='red';" onmouseout="this.style.color='';"> Hover over me </a>
- How it works: The inline JavaScript changes the element’s style when the mouse enters and resets it on exit.
- Pros: Purely inline in the sense you don’t need a separate
<style>
or.css
file. - Cons: Mixing JavaScript logic into HTML can reduce maintainability and accessibility. Also, it’s not truly using the
:hover
pseudo-class—just simulating it with events.
Best Practice
Use real CSS for :hover
, whether it’s an external stylesheet or an internal <style>
block. This approach is more maintainable, more accessible, and follows the semantic separation of concerns between content (HTML) and presentation (CSS).
Conclusion
- You can’t write
a:hover
inline via thestyle
attribute. - Use a stylesheet (best practice) or JavaScript event handlers as a workaround if you really need all styling in the HTML.