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

标签 html css flexbox

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

到目前为止,这是我的解决方案:http://codepen.io/roachdesign/pen/VeQKJK/

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

在使用绝对定位时,是否可以对 flexbox 或表格应用垂直居中?

County Badges

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>

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%;}

最佳答案

你可以使用转换

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

并且不要忘记清除 h2 的边距 这是一个working demo

关于html - 在 HTML 图像上水平和垂直居中文本(绝对定位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34955797/

相关文章:

html - 当我换行到新行时,如何让我的 flexbox 将 div 左对齐?

html - 表体设计不匹配

html - 如何将这些 anchor 标记移到右侧?

html - 如何在 VB.NET xml 字符串文字中嵌入变量 css 样式?

python - 我如何访问YouTube第一搜索结果?

css - 使用 --sourcemap 标志运行 Compass

css - React-Native:替代 flex-basis

html - 使用 flexbox 固定导航栏

HTML5 Canvas 叠加透明渐变

javascript - 使用 Nodejs 信息填充选择框