I would like to show a div when someone hovers over an <a>
element, but I would like to do this in CSS and not JavaScript. Do you know how this can be achieved?
Suppose we have two div elements with an id of one and two . We want to perform #one:hover and target a style change in #two . In order to do this, the two elements must be directly related: either a parent-child or sibling relationship.
You can apply :hover styles to any renderable element on a page. IE6 only supports that pseudo-class on links though.
You'll need a container div and at least one foreground div to cover the background (could be just an image). Then you'll want to target the parent on hover and change the foreground child. I used transform instead of animating a position property because it's more performant.
The :hover selector is used to select elements when you mouse over them. Tip: The :hover selector can be used on all elements, not only on links. Tip: Use the :link selector to style links to unvisited pages, the :visited selector to style links to visited pages, and the :active selector to style the active link.
You can do something like this:
div { display: none; } a:hover + div { display: block; }
<a>Hover over me!</a> <div>Stuff shown on hover</div>
This uses the adjacent sibling selector, and is the basis of the suckerfish dropdown menu.
HTML5 allows anchor elements to wrap almost anything, so in that case the div
element can be made a child of the anchor. Otherwise the principle is the same - use the :hover
pseudo-class to change the display
property of another element.
.showme { display: none; } .showhim:hover .showme { display: block; }
<div class="showhim">HOVER ME <div class="showme">hai</div> </div>
jsfiddle
Since this answer is popular I think a small explanation is needed. Using this method when you hover on the internal element, it wont disappear. Because the .showme is inside .showhim it will not disappear when you move your mouse between the two lines of text (or whatever it is).
These are example of quirqs you need to take care of when implementing such behavior.
It all depends what you need this for. This method is better for a menu style scenario, while Yi Jiang's is better for tooltips.
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