在html中实现图片相对于文字段落居中

本文介绍了一种使用table-cell布局方式使图片与文字在同一行显示,并根据不同情况调整垂直对齐的方法。适用于图片盒子高度小于或大于文字盒子的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

情况一:图片盒子高度小于文字盒子

实现效果:
这里写图片描述

步骤:
1.包含整体的div设置 display:table;(此元素会作为块级表格来显示(类似 <table>),表格前后带有换行符。) 。
2.将包含图片的div和包含文字的div分别设置 display:table-cell;(此元素会作为一个表格单元格显示(类似 <td>和 <th>)) ,此时图片和文字将处于同一行。
3.给包含文字的div设置 vertical-align:top;(把元素的顶端与行中最高元素的顶端对齐) ,实现文字向上对齐。
4.给包含图片的div设置 vertical-align: middle; (把此元素放置在父元素的中部。) ,实现图片相对于文字段落居中。

<!DOCTYPE html>
<html lang="zh-cmn-hans">
<head>
  <meta charset="utf-8">
  <title>图片居中 table-cell</title>

  <style>
    global-box {
      display: table;
    }
    .img-box {
      display: table-cell;
      background-color: yellow;
      vertical-align: middle;
    }
    .text-box {
      display: table-cell;
      background-color: #000;
      vertical-align: top;
    }
    p {
      background-color: lightblue;
    }
  </style>
</head>
<body>
  <div class="global-box">
    <div class="img-box">
      <img class="image" src="i-7.png">
    </div>
    <div class="text-box">
      <p>the first paragraph.</p>
      <p>the second paragraph.</p>
      <p>the third paragraph.</p>
    </div>
  </div>
</body>
</html>

情况二:图片盒子高度大于文字盒子

实现效果:
这里写图片描述

步骤:
将图片盒子和文字盒子的vertical-align属性值互换即可实现。

<!DOCTYPE html>
<html lang="zh-cmn-hans">
<head>
  <meta charset="utf-8">
  <title>图片居中 table-cell</title>

  <style>
    global-box {
      display: table;
    }
    .img-box {
      display: table-cell;
      background-color: yellow;
      vertical-align: top;
    }
    .text-box {
      display: table-cell;
      background-color: #000;
      vertical-align: middle;
    }
    p {
      background-color: lightblue;
    }
  </style>
</head>
<body>
  <div class="global-box">
    <div class="img-box">
      <img class="image" src="i-7.jpg">
    </div>
    <div class="text-box">
      <p>the first paragraph.</p>
      <p>the second paragraph.</p>
      <p>the third paragraph.</p>
    </div>
  </div>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值