Center a Large Image of Unknown Size Inside a Smaller Div with Overflow Hidden

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

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.

Center img inside smaller div not working as intended

Thanks to Abhitalks I found the problem I had with the flexbox. I've adapted the codepen so that it works with flexbox now.

For everyone who's seeking a solution to this, this is what your markup should be like:

HTML

<div class="container">
<img src=""/>
</div>

CSS

.container {
display: flex;
justify-content: center;
width: 50%; /* may have any percentage */
height: 100%; /* this is needed so that there will be no border at the bottom of the picture if window is resized */
overflow: hidden;
float: left; /* this can be left out if there is no textbox on the right side */
}

img {
min-width: 100%;
min-height: 100%;
}

Happy coding!

Center unknow image size with overflow hidden

You do have it vertically centered but the image has height 150px and your containing <div> is only 60px high. Making the <div> bigger than 150px and you will see it is aligned correctly.

EDIT

If you are intentionally trying to clip the image within the <div>, remove the <img> element and set it as the background using CSS.

div {
height:60px;
width:200px;
vertical-align:middle;
display:table-cell;
overflow:hidden;
background: no-repeat center url('http://www.w3schools.com/css/klematis4_big.jpg') ;
}

Why is header image not responsive?

background-size: contain vs cover

As Chris Coyier summarized here, background-size can provide various options, and cover might not be you're looking for here.

cover is focused on ensuring there's no space uncovered—practically extending the background image to all four edges beyond the containing boundaries. contain, on the other hand, is focused on ensuring there's no cropping happening on the background image—practically leaving uncovered areas blank.

If you intend your big image to remain intact, uncropped, and readable at all times, try adding the following to your .intro class.

background-size: contain;
background-color: #426CB4;

You already have your background-position: center as part of your background shorthand, so this should cover it. background-color line helps to fill the container with the same color as the logo background.



Related Topics



Leave a reply



Submit