I am looking for a way to center the image vertically, something that is similar to text-align center
. text-align
center is kinda efficient since you don't need to specify the width of the parent or the width of the children, it will automatically center its content. Is there any other way to do something like this for positioning image vertically?
Asked
Active
Viewed 222 times
3

Mr. Alien
- 153,751
- 34
- 298
- 278

user2310422
- 555
- 3
- 9
- 22
-
You can always use `vertical-align: middle`. – Vucko Oct 01 '13 at 05:52
-
Please show us some code. What have you tried and didn't work? – mavrosxristoforos Oct 01 '13 at 05:55
-
I haven't tried anything since I have no idea how to do it – user2310422 Oct 01 '13 at 05:57
-
Google `css vertical center image` has 148 million results, and you didn't try 1 of them? – mavrosxristoforos Oct 01 '13 at 05:58
-
Duplicate of http://stackoverflow.com/questions/7273338/how-to-properly-align-an-image-vertically – mavrosxristoforos Oct 01 '13 at 05:59
5 Answers
4
You can do it in 2 ways
Way 1 (Preferred), by using display: table-cell
div {
display: table-cell;
height: 100px;
border: 1px solid #f00;
vertical-align: middle;
}
Way 2, Using position: absolute;
and top: 50%
and than deduct 1/2 of the total height
of the image using margin-top
div {
height: 100px;
border: 1px solid #f00;
position: relative;
}
div img {
position: absolute;
top: 50%;
margin-top: -24px; /* half of total height of image */
}

Mr. Alien
- 153,751
- 34
- 298
- 278
-
@Mr.Alien Also see [Absolute Centering](http://codepen.io/shshaw/full/gEiDt) would be useful to add to the answer. – hitautodestruct Oct 01 '13 at 06:25
-
@hitautodestruct Not necessarily, but anyways I've added *preferred* there :) – Mr. Alien Oct 01 '13 at 06:27
-
@Mr.Alien Also see [this technique](http://css-tricks.com/centering-in-the-unknown) by chris coyer – hitautodestruct Oct 01 '13 at 06:28
0
in a parent div id parentDiv .. set image on background
#parentDiv
{
background:url(image.png) no-repeat center center;
height:500px;
width:500px;
}
or in child div do this thing...
position:absolute;
top:50%;

ShujatAli
- 1,376
- 2
- 14
- 26
0
All in the middle ...
<div id="container">
<div id="img"></div>
</div>
#container {
position: relative;
width:200px;
height:200px;
background:#040;
}
#container #img {
background: url("url_to_image.jpg") no-repeat center center;
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
}

Daniel
- 4,816
- 3
- 27
- 31
0
The solution you've got works for old browsers but in the near future (right now has like the 70% of the browser support) you can do this, a much simpler and elegant solution:
.container img{
width: 100%;
height: auto;
}
@supports(object-fit: cover){
.container img{
height: 100%;
object-fit: cover;
object-position: center center;
}
}

Vandervals
- 5,774
- 6
- 48
- 94