vertically alignment of a text inside a button with an image

心不动则不痛 提交于 2021-01-20 11:43:54

问题


In this CodePen you can see a <button> with an image and text inside (<span>). The problem is when the text got multiline. The second line of text is not immediately close to the first line and a big space appears (taking in count the height of the <img>).

My code (on CodePen):

button {
  width: 300px;
}
img {
  vertical-align: middle;
}
<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>

回答1:


You can use the following solution using flexbox:

* {
  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;
}
<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>



回答2:


can you try this 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>



回答3:


Try to do it like this way. There are other methods also, but this one is simple.

button {
  width: 300px;
}
button img {
  float:left;
  width:20%;
}
button span {
  float:right;
  width:80%;
}
<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>


来源:https://stackoverflow.com/questions/47464226/vertically-alignment-of-a-text-inside-a-button-with-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!