quantumbutterfly quantumbutterfly - 3 months ago 9
CSS Question

How to vertically align image

I am attempting to vertically align an image in a div, but everything I try won't work.

I am attempting to center it in a material design lite cell.

Here is my code:

CodePen

HTML:

<div class="mdl-grid">
<div class="mdl-cell mdl-cell--4-col">
a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>
</div>
<div class="mdl-cell mdl-cell--4-col">
<div class="imgholder">
<img src="http://i.stack.imgur.com/kq8EX.png" id="stackimg">
</div>
</div>
</div>


CSS:

.mdl-cell{
border: 1px solid black;
}
.imgholder{
width: 100%;
height:100%;
}
#stackimg{
width:50%;
float: right;
position: reletive;
top:50%;
vertical-align: middle;
}


Vertical-align: middle
isn't doing anything. Neither is
top: 50%
. The image does have a parent div with a defined height, so I'm not sure why it's not working.

Any help is appreciated.

Answer

You can vertically center your image by using translateY(). Give your container a position: relative; and then assign position: absolute; along with transform: translateY(-50%); to your image.

CSS

.imgholder{
  width: 100%;
  height: 100%;
  position: relative;
}

#stackimg{
  width: 50%;
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
}

CodePen

Comments