垂直对齐图像和两行文本

Align vertically an image and two lines of text

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

<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居中。有什么干净的方法可以使 texts/image 在 <a> 中居中?

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

您可以将 display: table-cell 添加到具有 class .buttonvertical-align: middle 的元素:

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: table-cell;/*change display to table-cell*/
  vertical-align: middle;/*add vertical align middle*/
}
span {
  font-size: 11px;
  color: #ccc;
  display: block;
}
img {
  vertical-align: middle;
}
<a class="button" href="">
  <img src="http://dummyimage.com/30x30/cf97cf/fff">Button
  <span>Button alt</span>
</a>

您还可以将 textspan 包装在 div 中,然后将 divimg 包装在另一个 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>

您可以将 imgspan 包裹在 div 中(以 class 居中)

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

然后添加这个 css:

.center {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

说明:将div的位置设置为顶部50%,然后将其移动到顶部50%的高度(translateY by -50%)