图标中心垂直和水平对齐

时间:2017-02-08 09:55:15

标签: html css

我正在尝试垂直和水平居中对齐我放在图像上方的小图标。

相关的html部分:

<li>
    <a href="#">
        <span class="test fa fa-play"></span>
        <img src="thumbnail1-l.jpg" alt="">
    </a>
</li>
<li>
    <a href="#">
        <span class="test fa fa-play"></span>
        <img src="thumbnail2-l.jpg" alt="">
    </a>
</li>
<li>
    <a href="#">
        <span class="test fa fa-play"></span>
        <img src="thumbnail3-l.jpg" alt="">
    </a>
</li>
<li>
    <a href="#">
        <span class="test fa fa-play"></span>
        <img src="thumbnail4-l.jpg" alt="">
    </a>
</li> 

CSS部分

.photo-list.cols-2 li {
    width: 50%;
}
.photo-list li {
    float: left;
    width: 25%;
    padding: 8px;
    opacity: .8;
    transition: opacity .3s ease-in-out;
}
.test{
    position: absolute;
    z-index: 1000000000;
    font-size: 30px;
    width: 60px;
    height: 60px;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
}

输出如下所示: enter image description here

对于如何正确对齐图标,我将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:2)

将所有img标记放在容器类的div中,并给出left:50%;和顶部:50%;属性img。参见下面的示例代码:

<!DOCTYPE html>
  <html>
    <head>
      <style>
      .container {
        position: relative;
        width: 50%;
      }

      .image {
        display: block;
        width: 100%;
        height: auto;
      }


      .text {
        color: white;
        font-size: 20px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        -ms-transform: translate(-50%, -50%);
        z-index:1;
      }
      </style>
    </head>
    <body>
    <div class="container">
      <img src="img_avatar.png" alt="Avatar" class="image">
      <div class="text">Kiran</div>
    </div>
  </body>
</html>

答案 1 :(得分:1)

添加到播放按钮

.test
.test {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
}