React中Img元素在IE11浏览器尺寸渲染异常求助
Hey there, I’ve dealt with this exact IE11 image sizing bug in React projects before—let’s walk through the most reliable fixes:
Why This Happens
IE11 has quirky handling of relative units (like em) for images, plus it often relies on explicit native width/height attributes more heavily than modern browsers. It also might miscalculate dimensions if box model settings aren’t locked in.
Solution 1: Explicit Pixel Dimensions + Box Model Reset
First, ditch the em units for direct px values (since 1.5em is typically 24px for a 16px base font) and enforce consistent box sizing:
.invert-image { width: 24px; height: 24px; box-sizing: border-box; /* Ensures padding/border don't shrink the image */ display: inline-block; /* Forces IE11 to treat it as a block-level element for sizing */ }
This removes any ambiguity from relative unit calculations in IE11.
Solution 2: Add Native Width/Height Attributes to the Img Tag
IE11 often ignores CSS-only dimensions for images unless the native HTML attributes are set. Update your JSX:
<img className="invert-image" src={commitFilled} alt="" width="24" height="24" />
You don’t need to add px here—these attributes default to pixel units, and IE11 will use them as a baseline for rendering.
Solution 3: Fallback to Background Image (If Needed)
If the above don’t work, swap the <img> tag for a <div> using background-image—IE11 handles background sizing much more reliably:
<div className="invert-image" style={{ backgroundImage: `url(${commitFilled})` }} aria-label="" /* Maintain accessibility since we're removing the img tag */ ></div>
Then update your CSS:
.invert-image { width: 24px; height: 24px; background-size: contain; background-repeat: no-repeat; background-position: center; }
Bonus: Lock Parent Font Size (If You Must Use Em)
If you need to stick with em units, explicitly set the font size on the parent container to eliminate IE11’s inconsistent inheritance:
.image-container { font-size: 16px; /* Explicit base font size */ } .invert-image { width: 1.5em; height: 1.5em; box-sizing: border-box; }
Start with Solutions 1 and 2 together—they resolve this issue 90% of the time for IE11. Let me know if you still run into trouble!
内容的提问来源于stack exchange,提问作者Saurav Dutta

