Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong height of div with img tag inside [duplicate]

I have a div with an image tag inside, and the div height appears to be a little larger than the image.

I could fix this problem by setting a specific height for the div (the same as the image), but I'm working with a responsive layout, and I don't want to set a specific height for the div, so that when the browser window scales (for example in mobile devices) the div will scale and maintain the ratio.

I need that the div height to be exactly as the image height.

This is the scenario:

<div class='box'><img src='image.jpg'></div>

Css is:

img { height: auto; max-width: 100%; width: auto; }

Does anybody know how to fix this problem?

Screenshot

like image 725
user1403825 Avatar asked May 18 '12 16:05

user1403825


People also ask

Why is div bigger than image?

The reason behind your issue is that you did not specify the width of the container but, in the same time, you set a width: 100%; for the image.

How do I resize a div to fit an image?

To auto-resize an image or a video to fit in a div container use object-fit property. It is used to specify how an image or video fits in the container. object-fit property: This property is used to specify how an image or video resize and fit the container.

How do I change the height of an image tag?

There is no command for changing an image size. Image dimensions are 'properties' which can be expressed in either the HTML <img> element, as width="150" height="100" attributes in the tag; or, the CSS as style rules applying to specific images.


2 Answers

The problem is that the image's natural styling gives it a little bit of margin on the bottom making it ugly to say the least. An easy fix is to just display: block, float: left on the image and the space should go away.

either that or you can play around w/ the border-collapsing on the image if you really don't want to float it. However, that's a solution that would probably cause more problems in the end.

so it's going to end up being something like

.box img {   display: block; /*inline block would be fine too*/   float: left; } 

hope that helps.

like image 189
Brodie Avatar answered Sep 17 '22 15:09

Brodie


The easiest way is to determine the vertical alignment of the image.

img {   vertical-align:middle; } 

http://jsbin.com/xozatu/edit?html,css,output

like image 25
Konstantin Barabator Avatar answered Sep 21 '22 15:09

Konstantin Barabator