将按钮内的文本与图像垂直对齐

时间:2017-11-23 22:51:56

标签: html css vertical-alignment

在此CodePen中,您可以看到<button>内有图片和文字(<span>)。问题是当文本得到多行时。第二行文字不会立即靠近第一行,并显示一个大空格(计算<img>的高度)。

我的代码(on CodePen):

&#13;
&#13;
button {
  width: 300px;
}
img {
  vertical-align: middle;
}
&#13;
<button>
  <img src="http://lorempixel.com/50/50/" />
  <span> Some Text some text some text some text some text some text some text some text</span>
</button>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:5)

您可以使用flexbox使用以下解决方案:

&#13;
&#13;
* {
  margin:0;
  padding:0;
  box-sizing:border-box;
}
button {
  align-items: center;
  display: flex;
  padding: 3px;
  justify-content: center;
  width: 300px;
}
button img {
  flex-shrink: 0;
  margin-right: 10px;
}
&#13;
<button>
  <img src="https://lorempixel.com/50/50/" alt="">
  <span>Some Text Some Text Some Text Some Text Some Text Some Text Some Text</span>
</button>
<button>
  <img src="https://lorempixel.com/50/50/" alt="">
  <span>Some Text</span>
</button>
<button>
  <img src="https://lorempixel.com/50/50/" alt="">
</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以尝试这个吗? https://codepen.io/anon/pen/qVKagg

button {
  width: 300px;
  display: flex;
  text-align:left;
}

img {
  vertical-align: middle;
  margin-right:5px;
}
<button>
<img src="http://lorempixel.com/50/50/" />
<span> Some Text some text some text some text some text some text some text some text</span>
</button>

答案 2 :(得分:0)

尝试这样做。还有其他方法,但这个方法很简单。

&#13;
&#13;
button {
  width: 300px;
}
button img {
  float:left;
  width:20%;
}
button span {
  float:right;
  width:80%;
}
&#13;
<button>
  <img src="http://lorempixel.com/50/50/" />
  <span> Some Text some text some text some text some text some text some text some text</span>
</button>
&#13;
&#13;
&#13;