在HTML图像上水平和垂直居中文本(绝对定位)

Mic*_*ach 0 html css flexbox

鉴于以下设计元素,我试图在html中包含图像,以便可以使用css过渡(悬停效果)操纵不透明度.

这是我迄今为止的解决方案:http://codepen.io/roachdesign/pen/VeQKJK/

这里的主要缺点是我使用手动垂直居中(绝对/顶部:4​​0%),这在缩小浏览器时变得明显.

在使用绝对定位时,是否可以使用flexbox或table进行垂直居中?

县徽章

HTML

<div class="badge-container">
  <a href="">
    <div class="badge">
        <img src="http://www.placehold.it/400x400/FF9999">
        <h2><strong>Cumberland</strong>County</h2>
    </div>
  </a>
  <a href="">
    <div class="badge">
        <img src="http://www.placehold.it/400x400/99FF99">
        <h2><strong>Dauphin</strong>County</h2>
    </div>
  </a>
  <a href="">
    <div class="badge">
        <img src="http://www.placehold.it/400x400/9999FF">
        <h2><strong>Lancaster</strong>County</h2>
    </div>
  </a>
  <a href="">
    <div class="badge">
        <img src="http://www.placehold.it/400x400/9F9F99">
        <h2><strong>Lebanon</strong>County</h2>
    </div>
  </a>
  <a href="">
    <div class="badge">
        <img src="http://www.placehold.it/400x400">
        <h2><strong>York</strong>County</h2>
    </div>
  </a>
</div>
Run Code Online (Sandbox Code Playgroud)

SCSS

.badge-container {display:flex; flex-direction:row; 
  .badge {position:relative;}
  h2 {position:absolute;
      top:36%;
      left:0; 
      right:0;
      text-align:center;
      strong {display:block;}
  }
}

img {max-width:100%;}
Run Code Online (Sandbox Code Playgroud)

Nar*_*k-T 8

您可以使用转换

h2 {
  position:absolute;
  top:50%;
  left:50%; 
  text-align:center;
  transform: translateX(-50%) translateY(-50%);
}
Run Code Online (Sandbox Code Playgroud)

并且不要忘记清除边缘h2 这里是一个工作演示