How to vertically align image and text in table ce

2020-07-14 05:42发布

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>

3条回答
我欲成王,谁敢阻挡
2楼-- · 2020-07-14 06:04

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>

查看更多
▲ chillily
3楼-- · 2020-07-14 06:10

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

查看更多
Fickle 薄情
4楼-- · 2020-07-14 06:18

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/

查看更多
登录 后发表回答