How to vertically align image and text in table cell?

时间秒杀一切 提交于 2020-01-01 14:57:01

问题


I'm trying to get the text to be on the right side and vertically center aligned with the image. How can I do that?

My current code:

<div style="display: table;">
  <div style="display: table-cell;"><img src="//dummyimage.com/100"></div>
  <div style="display: table-cell;">text</div>
</div>

回答1:


use CSS3 Flexible Box Layout:

from the documentation:

providing for the arrangement of elements on a page such that the elements behave predictably when the page layout must accommodate different screen sizes and different display devices. For many applications, the flexible box model provides an improvement over the block model in that it does not use floats, nor do the flex container's margins collapse with the margins of its contents.

your example with centered text to the right would look like this

#pageElement{display:flex; flex-wrap: nowrap; align-items: center}
<div id="pageElement">
  <div> <img src="http://placehold.it/350x150"> </div>
  <div> text </div>
</div>

I found this cheat-sheet very helpful and browser compatibility you find here




回答2:


In table cell, the default value of vertical-align is baseline. You can change that to middle for center align. Read more about it on MDN.

.table {
  display: table;
}
.table > div {
  display: table-cell;
  vertical-align: middle;
}
<div class="table">
  <div><img src="//dummyimage.com/100"></div>
  <div>text</div>
</div>



回答3:


Use td, tr and table.

<body>
<table>
   <tr width="100%;">
      <td width="50%;" valign="bottom">
      <img style="width:100%" src="https://s.w.org/images/home/screen-themes.png?1"/> </td>
      <td width="50%;" align="center" valign="center">  text dddddddddddd  </td>
   </tr>
</table>
</body>

See JsFiddle for example: https://jsfiddle.net/bndr6x4y/1/



来源:https://stackoverflow.com/questions/41655998/how-to-vertically-align-image-and-text-in-table-cell

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