Reputation: 13
I'm trying to center an image vertically inside a div - while keeping the proportions of the original image and only allowing it to be inside the div.
The original image source will change dynamically - it could be any size in theory: 200x150, 500x100, 500x500 etc.
What I have so far is this:
.outer {
position: relative;
background: gray;
width: 200px;
height: 150px;
}
.inner {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: gold;
overflow: hidden;
width: 200px;
height: 150px;
}
.inner img {
width: auto;
max-width: 100%;
max-height: 150px;
height: auto;
}
<div class="outer">
<div class="inner">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQwI_CFh8BfnYAn6pL7Pe1AX_LuxrvEs4HqL2qWNPoTvESUwj5hdw">
</div>
</div>
In this example - I want it to look like this:
https://i.sstatic.net/a7nPt.png
Is it possible with css?
Thanks in advance
Upvotes: 1
Views: 1059
Reputation: 893
Just add following to the image
margin: 0 auto;
display: block;
full code:
.outer {
position: relative;
background: gray;
width: 200px;
height: 150px;
}
.inner {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: gold;
overflow: hidden;
width: 200px;
height: 150px;
}
.inner img {
width: auto;
max-width: 100%;
max-height: 150px;
height: auto;
margin: 0 auto;
display: block;
}
<div class="outer">
<div class="inner">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQwI_CFh8BfnYAn6pL7Pe1AX_LuxrvEs4HqL2qWNPoTvESUwj5hdw"
</div>
</div>
Upvotes: 2