Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using only CSS, show div on hover over another element

Tags:

css

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?

like image 855
tetris Avatar asked Mar 06 '11 10:03

tetris


People also ask

How do I make hover affect another element?

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.

Can we use hover with div?

You can apply :hover styles to any renderable element on a page. IE6 only supports that pseudo-class on links though.

How do you make a hover effect a div?

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.

How do you hover over in CSS?

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.


2 Answers

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.

like image 60
Yi Jiang Avatar answered Sep 19 '22 09:09

Yi Jiang


.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.

like image 38
n00b Avatar answered Sep 17 '22 09:09

n00b