Search code examples
javascripthtmlcsspositioningvertical-alignment

Vertically centered absolute position div inside relative position parent - Works in Chrome, but centers to body in Safari etc?


I am trying to vertically center some text over an image that appears on a mouseover. I have come to a solution that works with chrome (15.0.874.106) on a mac (10.7.2), but it seems to have issues in Safari (5.1.1), odd since they are both webkit based. I believe it also has the same problem in Firefox.

The text is vertically centered in relation to the parent div in chrome, but seems to center to the body or window in Safari. Am I doing something wrong or does anyone have a better solution?

jsbin: http://jsbin.com/iceroq

CSS:

.content {
    width: 300px;
    position: relative;
}
.content-text {
    width: 100%;
    height: 100%;
    background: black;
    position: absolute;
    top: 0;
    left: 0;
    text-align: center;
    display: none;
}

HTML:

<div class="content">
    <div class="content-image">
        <img src="http://placehold.it/300x500/E01B4C" />
    </div>
    <div class="content-text">
        <a href="http://www.google.com">Google</a>
    </div>
</div>
.content-text a {
    color: white;
    position: relative;
    top: 50%;
    margin-top: -0.5em;
}

JS:

$(document).ready(function() {
    $('.content').hover(

    function() {
        $(this).children('.content-text').show();
    }, function() {
        $(this).children('.content-text').hide();
    });
});

Solution

  • I edited your jsbin: http://jsbin.com/iceroq/3

    The edits were all CSS changes to .content-text a. Making the link absolutely positioned and giving it a height allows you to know what margin-top to give it (half of the height).

    .content-text a {
      display: block;
      width: 100%;
      height: 20px;
      position: absolute;
      top: 50%;
      margin-top: -10px;
      color: white; 
    }