How can I display an image using the “em” unit?

2019-06-16 15:51发布

问题:

I've created a <div> with width:10em and height:5em.
Now I would like to display an <img> (GIF image) in this <div> with the exact same size. But apparently it doesn't "know" the em unit. It shows the picture in 10x5 pixels instead.

How can I display this <img> using the "em" unit?

回答1:

Use this code:

<html>
  <body>
    <p>This is 10em x 5em</p>
    <div style="width:10em; height:5em;">
    <img style="width:10em; height:5em;" src="logo.png" />
    </div>
  </body>
</html>

It works in Firefox 3.5, Internet Explorer 8 and Opera 10.0 Beta on Windows XP.



回答2:

You can style img with CSS:

img.MyImage {
    width: 10em;
    height: 5em;
}

<img class="MyImage" src="image.gif" />