如何实现响应式HTML Email的桌面端与移动端差异化内容适配
问题原因
- CSS语法错误:你在
<style>标签内使用了HTML注释<!-- Small devices -->,会直接导致后续媒体查询规则失效 - 显示逻辑写反:默认状态下你把桌面端元素设为隐藏,同时没有给桌面端状态下的移动端元素设隐藏规则,两种设备下都会出现展示异常
- 移动端容器未做适配:移动端版本的table固定宽度为620px,在小屏设备下会出现横向溢出
- 缺少样式优先级声明:HTML邮件客户端会覆盖默认样式,响应式规则需要加
!important提升优先级
修正后的完整代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <style> /* 默认桌面端样式 */ .desktop { display: block !important; } .mobile { display: none !important; } /* 小屏移动端适配 */ @media screen and (max-width: 480px) { .desktop { display: none !important; } .mobile { display: block !important; } .mobile table { width: 100% !important; } .mobile img { max-width: 100% !important; height: auto !important; } } </style> </head> <body style="margin:0; padding:0; background-color:#0d0d0d;"> <div class="desktop"> <table bgcolor="#0d0d0d" width="620" align="center" border="0" cellpadding="0" cellspacing="0"> <tr> <td bgcolor="#0d0d0d" align="center"> <table align="center" bgcolor="#0d0d0d" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" bgcolor="#0d0d0d"> <!--Image Version 1 Desktop --> <img src="CarImage_v1.png" style="display:block; border:0" /> </td> </tr> <tr> <td align="center" bgcolor="#0d0d0d"> <!-- Car Text Version 1 Desktop --> <p style="font-family: Arial; color:#c2c2c2; font-size:20px; margin:20px 0 0 0;"> Superior en todo. <br/> Incluso en clase. </p> </td> </tr> </table> </td> </tr> </table> </div> <div class="mobile"> <table bgcolor="#0d0d0d" width="620" align="center" border="0" cellpadding="0" cellspacing="0"> <tr> <td> <table align="center" bgcolor="#0d0d0d" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" bgcolor="#0d0d0d"> <!--Image Version 2 Mobile --> <img src="CarImage_v2.png" style="display:block; border:0" /> </td> </tr> <tr> <td align="center" bgcolor="#0d0d0d"> <!-- Car Text Version 2 Mobile --> <p style="font-family: Arial; color:#c2c2c2; font-size:20px; margin:20px 0 0 0;"> Cuando la deportividad y <br/> la clase se entiende </p> </td> </tr> </table> </td> </tr> </table> </div> </body> </html>
关键调整说明
- 修复了CSS内的HTML注释错误,改用CSS标准注释
- 调整了默认显示逻辑:桌面端默认显示desktop元素、隐藏mobile元素,小屏设备下反过来
- 给移动端容器和图片增加了自适应规则,避免宽度溢出
- 所有响应式规则都加了
!important,避免被邮件客户端默认样式覆盖 - 补充了HTML邮件标准的DOCTYPE和meta视口声明,提升各客户端兼容性
内容的提问来源于stack exchange,提问作者javi-ur96
相关产品推荐
相关产品推荐

