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>
Desired result. (Ignore opacities etc, just note the positioning).
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
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.
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 ).
Just add display:flex and justify-content: center to the . content .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With