html - 垂直对齐图像和两行文本

标签 html css vertical-alignment

我在这里读了很多文章,很多帖子,但不幸的是我不能将两行文字和一张图片垂直居中。

<a class="button" href="">
    <img src="http://dummyimage.com/30x30/cf97cf/fff">
    Button
    <span>Button alt</span>
</a>

我想要图像旁边的 2 行(居中),并在 .button 中垂直居中整个内容.

body {
    padding: 20px;
}

.button {
    background: #000;
    color: #fff;
    text-decoration: none;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    height: 120px;
    padding: 30px 50px;
    display: inline-block;
}

span {
    font-size: 11px;
    color: #ccc;
    display: block;
}

img {
    vertical-align: middle;
}

在 CSS-Tricks 我找到了一篇文章,但我不想使用 position:absolute居中。有没有什么干净的方法可以将 <a> 中的文本/图像居中? ?

JsFiddle:http://jsfiddle.net/7fx3eozd/

最佳答案

您还可以将 textspan 包裹在 div 中,然后包裹 div img 在另一个 div 中,然后添加这些类:

同时在你的 img 上添加 display: inline-block;

    .center {   
      position: relative;
      top: 50%;
      transform: translateY(-50%); 
    }
   .btnText {
      vertical-align: middle; 
      display: inline-block;
    }

JSFIDDLE DEMO


body {
    padding: 20px;
}

.button {
    background: #000;
    color: #fff;
    text-decoration: none;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    height: 120px;
    padding: 30px 50px;
    display: inline-block;
}
span {
  font-size: 11px;
  color: #ccc;;
  display: block; 
}
img {
  vertical-align: middle; 
  display: inline-block;
}
.center {  
  position: relative;
  top: 50%;
  transform: translateY(-50%); 
}
   .btnText {
  vertical-align: middle; 
  display: inline-block;
}
<a class="button" href="">
  <div class="center">
      <img src="http://dummyimage.com/30x30/cf97cf/fff">
      <div class="btnText">
        Button  
        <span>Button alt</span>
      </div>
  </div>
</a>

关于html - 垂直对齐图像和两行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32045458/

相关文章:

javascript - 在 JS 客户端表单验证中联系服务器

css - 较低的百分比无法正常工作

html - 框外阴影与白色阴影相结合

css - 试图垂直对齐容器 div 中的两个 float div

html - 垂直居中和居中对齐文本并为 div 添加边距?我迷路了

android - 使 RecyclerView 垂直

html - Ckeditor 4 - 如何更改包括下划线在内的链接颜色?

javascript - Ajax 和动态更改 URL?

javascript - 固定位置在 IE 中不起作用

jquery - 动画完成后写入具有淡入效果的文本(html)