Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fit an image inside a box and vertical align it

Tags:

html

css

I need to give access to the users to upload what ever pixels they want but it will be over 100x100 for their profile pic. The pic will be contained in SQUARE box. But the problem is, when I upload a 100x100 or sizes similiar to that, it works good as expected. But when I upload an image with the pixels of 640x360 or anything similar to that sort (or widescreened), the image is scaled into the box well but however, it is not vertically aligned. I want the vertical-align to be in the middle, so how do I do that?

CSS:

#imgbox {
  height:100px;
  width:100px;
  overflow:hidden;
  border:solid 1px #000;
  margin-left:10px;
  margin-top:10px;
}
#imgbox img {
  width:100%;

  position:relative;
  //I want the vertical align of the image to be in the center
}

Here: http://jsfiddle.net/ZdW9h/1/

like image 574
Cole Avatar asked Jan 15 '23 11:01

Cole


2 Answers

A couple things -

Use a class for your imgbox elements, IDs are used for selecting a single element in a given document.

Secondly, I suggest using one div with background-image properties, this way you can position it relatively.

HTML

<div class="imgbox" style="background-image: url(http://plants.montara.com/ListPages/FamPages/showpix/ranunculaS/aqufor_a.JPEG)"></div>
<div class="imgbox" style="background-image: url(http://pictures.inspirationfeed.netdna-cdn.com/wp-content/uploads/2010/06/Evolution_by_will_yen-500x500.png)"></div>

CSS

.imgbox {
    height: 100px;
    width: 100px;
    overflow: hidden;
    border: solid 1px #000;
    margin-left: 10px;
    margin-top: 10px;
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;
}

JSFiddle

like image 106
Austin Brunkhorst Avatar answered Jan 21 '23 14:01

Austin Brunkhorst


If you set a line-height on your container div, you can then use vertical-align on the image to position it. Also, you should use max-width and max-height to make sure the image is always contained within the box (assuming that's what you want).

http://jsfiddle.net/ZdW9h/7/

And here is the updated CSS:

#imgbox {
    height:100px;
    width:100px;
    line-height: 100px;
    overflow:hidden;
    border:solid 1px #000;
    margin-left:10px;
    margin-top:10px;
}
#imgbox img {
    max-width:100%;
    max-height: 100%;
    vertical-align: middle;
}
like image 24
matthewpavkov Avatar answered Jan 21 '23 13:01

matthewpavkov