开发者

CSS: layer two elements centered

How can I do this:

  1. an image
  2. a simple small DIV on top of the image, centered vert/horiz, which doesn't a开发者_StackOverflow中文版ppear until the image is rolled-over


Try this:

<div style="position:relative;top:0;left:0;">
    <img src="path/2/img.png" style="z-index:1;"
         onmouseover="document.getElementById('hidden').style.display='block';">
    <div id="hidden" style="display:none;position:absolute;z-index:10;"></div>
</div>

If it works for you, clean it up before you deploy it! :)

NOTE: div#hidden is not yet centered over the image. If you know the width and height of it in advance, you can use this method:

#hidden {
    top:50%;
    left:50%;
    margin-top: -(heightOfHiddenDiv/2)px
    margin-left: -(widthOfHiddenDiv/2)px
}

Otherwise you will need to get the computed values of width and height in JavaScript.


If you can have a fixed width and height for the <div>, then I’d suggest this:

HTML

<div class="hover_image">
    <img width="250" height="300" src="http://pauldwaite.me.uk/images/professional.jpg" />
    <div class="overlay">Hello!</div>
</div>

CSS

.hover_image {
    position: relative;
    float: left;
}

.hover_image .overlay {
    visibility: hidden;
    position: absolute;
    top: 50%;
    left: 50%;
    width: 100px;
    height: 3em;
    margin: -2em 0 0 -55px;
    padding: .5em 5px;
    background: #006;
    color: #fff;
}

.hover_image:hover .overlay {
    visibility: visible;
}

http://jsfiddle.net/ZKXgw/

You may need to add some JavaScript to make .hover_image:hover work in earlier versions of IE, which didn’t support :hover on anything except links.

If you can’t have a fixed width/height, it’ll be a lot tricker to achieve.


Things aren't really clear to me, any way you can play with the CSS/style of the element to work around on this.

To center an element you can set the top and left by 50% where its position is set to absolute. Then set the margin-top the half size of its height in negative, and the margin-left the half size of its width in negative.

To place the div in top of the image, its z-index must be higher than the image. But first the image must have the higher z-index until its not rolled-over.

To show the div on top of the image change the z-index of the image lower then the div. Using hover or onMouseOver event. There other ways of doing this, base on your needs.

See jsfiddle in action


  1. You can use z-index property with absolute positioning to place the div on top of the image. Since you want this to be hidden, set the "display" property in css to "none".

  2. The second part of your question can be accomplished by using a javascript function that you can call onmouseover [ http://www.w3schools.com/jsref/event_onmouseover.asp ]. All the function would have to do is change the "display" property of the element from "none" to "block".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜