简体   繁体   中英

DIV with text over an image on hover

OKay first off this is really really similiar to the http://dribbble.com homepage.

In the simplest form possible. I have an image, and i'm trying to CSS it so that when i hover over the image, a DIV shows up with some text and a partially transparent background color.

I have no idea how to do this..

Here is a start. IE6 won't do this, unless you make the parent an anchor ( a ).

HTML

<div class="container">
    <img src="something.jpg" alt="" />
    <div>some text</div>
</div>

CSS

.container div {
    display: none;
    opacity: 0.7; /* look into cross browser transparency */
}

.container:hover div {
    display: block;
}

@alex, I think he wants the text to appear over the image, not under it. Two ways to fix this:

  1. Add position:absolute to the div containing the text.
  2. Use a background-image instead of an img tag.

I'd go with 1, as it's better semantically and better for accessibility to use img tags for content-bearing images.

If what you want to obtain is an effect like that on Dribbble page, then you do not need to create a div over an img .

It's sufficient to have 2 versions of the image, one normal and one desaturated and with luminosity increased (or something like that, to give the impression of "transparency").

Now you create a div with the image as background and on mouseover you switch background and add the text. On mouseout you revert the changes.

EDIT: Of course in practice you will dynamically assign the images name (eg with PHP), but that's another story. You may even automagically generate the "transparent" image by using GD libraries I guess.

A little example:

CSS:

.squareImg
    {
    display: block;
    width: 100px;
    height: 100px;
    background-image: url("100x100.jpg"); 
    }

.squareImgOver
    {
    display: block;
    width: 100px;
    height: 100px;
    background-image: url("100x100transp.jpg"); 
    }

HTML

<div id="mydiv" class="squareImg" onmouseover="writeText();" 
    onmouseout="eraseText()"></div>

JS

function writeText()
    {
    var d = document.getElementById("mydiv");
    d.className = "squareImgOver";
    d.innerHTML = "something here!";
    }

function eraseText()
    {
    var d = document.getElementById("mydiv");
    d.className = "squareImg";
    d.innerHTML = "";
    }
</script>

我建议使用jQuery,因为很容易说“ mouseover”会触发另一件事。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM