Reputation: 9806
I have an img
that I've scaled to half size via;
transform: scale(0.5);
As seen above, the result is such that an invisible margin/padding is evident on the top & left of the image (equaling half the size the original image). Inspecting the resulting img
in chrome dev tools shows that no margin or padding is evident.
If I know the size of the image prior, I can set position: absolute
and offset the top
& right
values to position it in the center of the container div. This will not however work with dynamic image sizes.
How can I center the scaled image within the parent div without needing to know the image size prior?
codepen and snippet:
#container {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 300px;
height: 100px;
background: #AAA;
}
#image {
transform: scale(.5);
}
<div id="page">
<div id="container">
<img id="image" src="//unsplash.it/500/160?image=10" />
</div>
</div>
Expected result;
Upvotes: 2
Views: 102
Reputation: 122037
If scale is constant 0.5
you can use left/right 50%
and translate(-100%, -100%)
, width and height of image and container can be dynamic and this will work.
#container {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 300px;
height: 100px;
background: #AAA;
}
#image {
transform: scale(.5) translate(-100%, -100%);
position: absolute;
left: 50%;
top: 50%;
}
<div id="page">
<div id="container">
<img id="image" src="//unsplash.it/500/160?image=10" />
</div>
</div>
Upvotes: 2
Reputation: 3870
Your img element is bigger than your container.
use;
max-width: 100%;
and also;
transform-origin: 50% 50%;
Upvotes: 0
Reputation: 42352
Adding max-width: 100%
to the #image
seems to center the image inside the container.
#container {
position:absolute;
top: 0;
bottom:0;
left: 0;
right:0;
margin: auto;
width: 300px;
height: 100px;
background: #AAA;
}
#image {
transform: scale(.5);
max-width: 100%;
}
<div id="page">
<div id="container">
<img id="image" src="//unsplash.it/500/160?image=10" />
</div>
</div>
Check it out and let me know your feedback. Thanks!
Upvotes: 0