curious1 curious1 - 2 months ago 6
CSS Question

How to make a non-background image display in the center of a smaller div

I have the following HTML:

<div style="width:400px;height:300px;overflow:hidden;">
<img src="http://d39kbiy71leyho.cloudfront.net/wp-content/uploads/2016/05/09170020/cats-politics-TN.jpg" />
</div>


Here is the jsfiddle: https://jsfiddle.net/mddc/j2vw29c6/12/

The image is 600px in width. It cannot be a background image. So the image's center in the width direction is not displayed in the center (width direction) of the parent div. Note that the image cannot be responsive.

Thanks!

Answer

meet the command which basically center everything :)

top: 50%; left: 50%;
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);

Demo: https://jsfiddle.net/j2vw29c6/14/

Comments