Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center a large image of unknown size inside a smaller div with overflow hidden

Tags:

html

css

I would like to center an img inside a div without javascript and without background-images.

Here is some example code

<div>      <img src="/happy_cat.png"/>  </div> 
  • I don't know the size of the img and it should be able to exceed the width of the parent
  • I don't know the width of the parent div (it is 100%)
  • The parent div has a fixed height
  • The image is larger than the parent and the parent has overflow:hidden
  • Only need to support modern browsers

Desired result. (Ignore opacities etc, just note the positioning).

enter image description here

I know this can be done easily with background images but that isn't an option for me. I could also use javascript but it seems like a very heavy handed way to achieve this.

Thanks!

Jack

like image 587
JackMahoney Avatar asked Oct 30 '13 04:10

JackMahoney


People also ask

How do I center a large image in a div?

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 image overflow in CSS?

It is pretty easy to do if the image is smaller than the surrounding div: margin-left: auto; margin-right: auto; display: block; But when the image is larger than the div it simply starts at the left edge and is off center to the right (we are using overflow: hidden ).

How do you center overflow in CSS?

Just add display:flex and justify-content: center to the . content .


1 Answers

What about this:

.img {    position: absolute;    left: 50%;    top: 50%;    -webkit-transform: translateY(-50%) translateX(-50%); } 

This assumes that the parent div is positioned relatively. I think this works if you want the .img relatively positioned rather than absolutely. Just remove the position: absolute and change top/left to margin-top and margin-left.

You'll probably want to add browser support with transform, -moz-transform etc.

like image 137
Evan Layman Avatar answered Sep 28 '22 05:09

Evan Layman