javascript - 相对位置父级内垂直居中的绝对位置 div - 在 Chrome 中工作,但在 Safari 等中以主体为中心?

标签 javascript html css positioning vertical-alignment

我试图将一些文本垂直居中放置在鼠标悬停时出现的图像上。我找到了一个在 mac (10.7.2) 上与 chrome (15.0.874.106) 一起使用的解决方案,但它似乎在 Safari (5.1.1) 中有问题,这很奇怪,因为它们都是基于 webkit 的。我相信它在 Firefox 中也有同样的问题。

文本在 chrome 中相对于父 div 垂直居中,但在 Safari 中似乎以主体或窗口为中心。我做错了什么或者有人有更好的解决方案吗?

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();
    });
});

最佳答案

我编辑了你的 jsbin:http://jsbin.com/iceroq/3

这些编辑都是对 .content-text a 的 CSS 更改。使链接绝对定位并给它一个 height 可以让你知道给它什么 margin-top(高度的一半)。

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

关于javascript - 相对位置父级内垂直居中的绝对位置 div - 在 Chrome 中工作,但在 Safari 等中以主体为中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7920387/

相关文章:

jquery - 删除悬停时内置的工具提示?

css - 将两个 float 放在一个div中

javascript - jQuery:删除大于和小于的选择选项

javascript - 让 jquery 忽略 href

javascript - 通过reducer获取相同数据或空数据

javascript - 居中 div 之前的 div

javascript - 当给定值时,图像不显示常量

html - bootstrap grid - 移动和桌面排列

python - 动态改变 HTML 源代码

html - 使用 UI Kit 添加动态边距