html - 无法在图像悬停时将文本居中

标签 html css image webkit hover

我正在为我的网站设置一个新主页。它将有一个由四个图像组成的 2x2 网格,这些图像随窗口改变大小,并且它们都有一个悬停文本。到目前为止,我能够做所有事情,但我在某一点上遇到了困难,这可能有一个我找不到的简单答案。当我将鼠标悬停在图像上时,无论窗口大小如何,我都想让文本居中。但我找不到正确的方法来做到这一点。我尝试过的方法要么不在垂直和水平方向居中,要么在调整窗口大小时文本偏离中心。任何帮助,将不胜感激。谢谢!

这是我的代码:jsfiddle

HTML

<section id="photos">
    <a href="/portfolio/test1.shtml" class="darken"><img src="image1"><span>GALLERY ONE</span></a>
    <a href="/portfolio/test2.shtml" class="darken"><img src="image2"><span>GALLERY TWO</span></a>
    <a href="/portfolio/test3.shtml" class="darken"><img src="image3"><span>GALLERY THREE</span></a>
    <a href="/portfolio/test4.shtml" class="darken"><img src="image4"><span>GALLERT FOUR</span></a>
</section>

CSS

#photos {
/* Prevent vertical gaps */
line-height: 0;
margin-left:150px;

-webkit-column-count: 2;
-webkit-column-gap:   0px;
-moz-column-count:    2;
-moz-column-gap:      0px;
column-count:         2;
column-gap:           0px;
}

#photos img {
/* Just in case there are inline attributes */
width: 100% !important;
height: auto !important;
}

a.darken {
display: inline-block;
background: black;
padding: 0;
position:relative;  
}

a.darken img {
display: block;

-webkit-transition: all 0.2s linear;
   -moz-transition: all 0.2s linear;
    -ms-transition: all 0.2s linear;
     -o-transition: all 0.2s linear;
        transition: all 0.2s linear;
}

a.darken:hover img {
opacity: 0.3;           
}

a.darken span{visibility:hidden; font-size:16px;}
a.darken:hover span{color:#fff; visibility:visible;
-webkit-transition: all 0.2s linear;
   -moz-transition: all 0.2s linear;
    -ms-transition: all 0.2s linear;
     -o-transition: all 0.2s linear;
        transition: all 0.2s linear;
}

最佳答案

这在旧版浏览器中不起作用,但您可以结合使用“翻译”和绝对定位来垂直和水平对齐文本。只需添加以下内容:

a.darken span{
  visibility:hidden; 
  font-size:16px;

  /* new styles below: */
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  line-height: 100%;
}

举个例子: http://jsfiddle.net/bk2Sd/2/

关于html - 无法在图像悬停时将文本居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20861532/

相关文章:

image - 使用blockproc或im2col在图像上重叠滑动窗口?

html - Bash 字符串格式化

html - 如果高度不同,如何使用 Twitter Bootstrap 制作响应式照片网格

javascript - 如果 src 为空则隐藏图像

java - 如何使 ImageIO 从 InputStream :Java 读取

css - 在基于 CSS 的绝对定位 UL 对齐(下拉效果)方面需要帮助

css - 为什么我的列不能正确对齐?

javascript - 为什么 .prop ("type") 在日期时间输入上返回 "text"?

jquery - 找到显示为 : block 的最后一个可见 div

html - 如何获得具有固定宽度列的 <table> 以填充其容器的整个宽度?