Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to horizontally center an img in a narrower parent div

Tags:

css

I need to center images that will be wider than the parent div that contains them. the parent div is a fixed width and has the overflow set to hidden.

<div style='overflow:hidden; width:75px height:100px;'>
    <img src='image.jpg' style='height:100px;' />
</div>

I must use an image as the child element because I need to resize the thumbnail dimensions and cannot rely on background-size since it is not supported on older versions of mobile safari which is a requirement. I also cannot use javascript for this, so it must be a css solution.

One more thing to note is that widths will vary between images, so I can't just use absolute positioning on the child element at a hard-coded offset.

Is this possible?

UPDATE:

for posterity, I've just found out that this can be accomplished on the older versions of mobile safari by using

-webkit-background-size:auto 100px; 

of course, the background will be set as usual using 50% for left positioning. If you need this to work on another browser, the accepted solution is probably the best, but since this question was related to the iphone, this solution is a little cleaner.

like image 549
kona Avatar asked Nov 04 '11 22:11

kona


People also ask

How do I center an image in a div horizontally?

Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.

How do I center an object horizontally in a div?

To center a div horizontally on a page, simply set the width of the element and the margin property to auto. That way, the div will take up whatever width is specified in the CSS and the browser will ensure the remaining space is split equally between the two margins.

How do you center an image horizontally using the margin property?

To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.


Video Answer


1 Answers

How adverse are you to extra markup? Also, is there a max size for the images? For example, if your max image width is 225px then you could try:

<div class="frame">
  <div>
    <img src="image.jpg"/>
  </div>
</div>

.frame {
  overflow: hidden; 
  width: 75px;
  height: 100px;
  position: relative;
}
.frame > div {
  position: absolute;
  left: -5075px;
  width: 10225px;
  text-align: center;
}
.frame img {
  height: 100px;
  display: inline-block;
}

A fiddle example here: http://jsfiddle.net/brettwp/bW4xD/

like image 113
Brett Pontarelli Avatar answered Oct 22 '22 18:10

Brett Pontarelli