How to keep images in an HTML template inside Outlook from expanding unnecessarily with React?

余生长醉 提交于 2021-01-29 05:20:10

问题


I'm creating a email generator using React. I'm rendering tables (since that's what an email must have).

In most email browsers the email looks decent, except in Outlook which expands the images and ruins the layout.

Here is the specific component that renders the images:

const Ad = ({ image, link, hasDivider, styles = localStyles }) => (
  <>
    <Grid.Row className={styles.container}>
      <a href={link}>
        <span
          dangerouslySetInnerHTML={{
            __html: `
            <!--[if mso]>
            <table width="100%">
              <tr>
                <td>
                  <img width="100%" src=${image}
                  alt="ad" style="text-align: right; width: 100%; border: 0;
                  text-decoration:none;
                  vertical-align: baseline;">
                </td>
              </tr>
            </table>
            <div style="display:none">
            <![endif]-->`
          }}
        />
        <Img className={styles.image} src={image} alt="ad" />
        <span
          dangerouslySetInnerHTML={{
            __html: `
            <!--[if mso]>
            </div>
            <![endif]-->
            `
          }}
        />
      </a>
    </Grid.Row>
    {hasDivider && (
      <Grid.Row>
        <Divider />
      </Grid.Row>
    )}
  </>
)

Img component:

const Img = ({ src, alt, className, styles = localStyles, style = {} }) => {
  return (
    <img
      src={src}
      alt={alt}
      style={style}
      className={cx(styles.img, className)}
    />
  )
}

I'm using "email conditionals" for this which kind of works in more modern Outlook versions.


回答1:


In the Outlook on Windows (from 2007 to 2019, using Word's rendering engine), percentage widths on <img> elements are based on the image file’s physical width, not the parent element’s width as one should expect in CSS. So if your image is 100px wide, width="100%" will equal to 100px. And if your image is 2000px wide, it will equal 2000px. The appropriate solution for Outlook is to use a fixed width in pixels via the HTML width attribute, and use a width:100%; styles for other clients in an inline style (which Outlook will ignore).

You're going to need to update your Img component to include the image’s width and render it with something like this:

<img width="${width}" src=${image}
                  alt="ad" style="text-align: right; width: 100%; border: 0;
                  text-decoration:none;
                  vertical-align: baseline;">


来源:https://stackoverflow.com/questions/65093699/how-to-keep-images-in-an-html-template-inside-outlook-from-expanding-unnecessari

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