首发于 银匠屋
任意高度图片与文字第一行的垂直居中对齐

任意高度图片与文字第一行的垂直居中对齐

没有什么对齐是flex解决不了的别用vertical-align了


一句话总结

通过给图片设置flex-start上对齐,然后在图片旁边加入一个看不见的字,将该字设置成和文本大小一致并隐藏,用这个看不见的字撑起图片高度的垂直居中。

单/多行文字+icon垂直居中

效果如图:

图片比文字大
图片比文字小
图片对齐多行文字
<!DOCTYPE html>
<html lang="en">
    <style>
        .father{
            /*  flex布局 */
            display: flex;
            /* 子元素垂直居中 */
            align-items:center;;
    </style>
</head>
    <div class="father">
        <img src="https://p0.meituan.net/travelcube/602782cdcbae46b3506583cb5c228cd3507.png" />
        <div class="text">
        </div>
    </div>
</body>
</html>

图片居中对齐多行文字中的第一行

对齐第一行文字的腰部
<!DOCTYPE html>
<html lang="en">
    <style>
        .father{
            display: flex;
            align-items:flex-start;;
            font-size: 100px;;
        .icon-container{
            display: flex;
            align-items: center;;
        .hidden{
            width:0;
            /* 这里可以用 等方法 */
            overflow: hidden;
    </style>
</head>
    <div class="father">
        <div class="icon-container">
            <img src="https://p0.meituan.net/travelcube/602782cdcbae46b3506583cb5c228cd3507.png" />
            <span class="hidden">无</span>
        <div class="text">
            文本内容文本内容文本内容文本内容
</body>
</html>

图片居中对齐多行文字中的第一行(进阶)

<style>
  .parent {
    outline: 1px solid red;
    font-size: 50px;
    line-height: 1.5;
  .icon-container {
    outline: 1px solid red;
    display: inline-flex;
    align-items: center;
    vertical-align: top;
    /* 可以用来调节首行缩进距离 */
    /* margin-right:-10px; */
  img {
    width: 10px;
    height: 10px;
  .hide {
    width: 0;
    overflow: hidden;
</style>
<div class="parent">
  <div class="icon-container">
    <img class="icon"
      src="https://cdn.sm.cn/static/21/11/24/9645dd3bf73be9f70f8a1411be952f68.png"
      alt="" />
    <span class="hide">x</span>
  中国人不骗中国人
  中国人不骗中国人
  中国人不骗中国人