1

What are the other CSS definitions happening here that constrain the <img> element?

Here is an example, I'm only defining width and height, but you will see that the element uses the entirety of the image and scales it to fit, while the <div> element uses the image at 100% scale and clips around the width and height.

How can I control the <img> to behave more like the <div>?

http://jsfiddle.net/x93uL/

<img src="http://i.eho.st/pjw35bzm.jpg" width="140" height="140" />

<div id="img"></div>

<style>
#img{
    width: 140px;
    height: 140px;
    background: url(http://i.eho.st/pjw35bzm.jpg);
}
</style>
RenaissanceProgrammer
  • 404
  • 1
  • 11
  • 30

2 Answers2

1

Just for the record. You should use the background-size property if you want to make a div and its background to appear as an img.

Check this jsfiddle.

HTML:

<img id="Img" src="http://goo.gl/OJhO2s" />
<div id="ImgBg"></div>

CSS:

#Img {
    width: 100px;
    height: 100px;
}

#ImgBg {
    width: 100px;
    height: 100px;
    background: url('http://goo.gl/OJhO2s');
    background-size: 100px 100px;
    background-repeat: no-repeat;
}

The background-repeat property is optional and only as a fallback measure in case your div happens to be bigger than the background's size.

In an opposite case:

  • img elements can have the block display property and behave just like divs. Then you can float and hide them just like any regular div. Their display property is by default set to inline-block.

But img elements by default always scale their image up to the size they're set to, so there's no official way to make them clip their contents. Your only alternative are divs with a background image.

arielnmz
  • 8,354
  • 9
  • 38
  • 66
  • 1
    I think the OP wants the opposite: "How can I control the `` to behave more like the `
    `".
    – showdev Jun 16 '14 at 23:46
  • @arielnmz showdev is correct, I'm working with a sprite sheet but a platform that was creating `` elements. I need the solution for sizing the `` element as a `
    ` naturally sizes the image. @showdev your solution for using `clip: rect()` and `position:absolute` is what I was looking for.
    – RenaissanceProgrammer Jun 16 '14 at 23:53
  • 1
    @RenaissanceProgrammer he is indeed. I've checked your question again and I realized that's exactly what you need. Oh well. My answer could stay here just for the record. – arielnmz Jun 16 '14 at 23:57
1

You can use CSS clip to crop an image, but it only works on elements with position:absolute.

<img src="http://i.eho.st/pjw35bzm.jpg" class="two" />
img.two {
    position:absolute;
    clip: rect(0px, 140px, 140px, 0px); 
}

Working Example

showdev
  • 28,454
  • 37
  • 55
  • 73