Reputation: 6802
i currently try to a response design. I need to keep the image centered while the parent div gets smaller.
See image as explanation:
I dont want to use it as background. The following code will always place it at the top left of the div box
<div id="img_wrap">
<img src="test.png" id="img" />
</div>
<style type="text/css">
#img_wrap {
overflow: hidden;
text-align: center;
}
</style>
Upvotes: 2
Views: 89
Reputation: 951
For making the image center
<div id="img_wrap">
<img src="http://placehold.it/350x150" id="img" />
</div>
<style type="text/css">
#img_wrap{
position: relative;
width: 200px;
height:150px;/*give the image height*/
background: red;
overflow:hidden;
display: inline-block;
}
#img{
position: absolute;
left: 50%;
transform: translateX(-50%);
}
</style>
Here is the demo http://jsfiddle.net/adarshkr/p1p100h7/1/
Upvotes: 0
Reputation: 269
If Old browser compatibility is not an issue you can use following
#img_wrap img
{
display:flex;
-ms-flex-pack:stretch;
-webkit-box-pack:stretch;
justify-content:center;
}
Upvotes: 0
Reputation: 6937
Here's an example
#img_wrap{
position: relative;
overflow: hidden;
/* arbitrary container size */
width: 7rem;
height: 16rem;
}
#img{
position: absolute;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
}
The trick is that the image is absolutely placed at the center, 50% of its parent container width, then shifted left 50% of it's own width with the transform.
Upvotes: 2
Reputation: 951
Here is the solution, to make image responsive..
<div id="img_wrap">
<img src="test.png" id="img" />
</div>
<style type="text/css">
#img_wrap{
position:relative
}
#img_wrap img{
max-width:100%;
height:auto;
margin:0 auto;
display:block;
}
</style>
Hope it helps...
Upvotes: -1