0

I am currently centring an image in the horizontal using:

.centeredImage
    {
    text-align:center;
    display:block;
    }

<!DOCTYPE html>
<html>

<head>
   <title>My Site</title>
   <link href="style.css" rel="stylesheet">

</head>

<body>

   <p class="centeredImage"><img id ="img" src="smallslide1.png"></p>

</body>
</html>

This works fine but I want to centre it vertically too. Not sure how to do about this. I tired to wrap it in a separate div

.centeredVert{
    vertical-align: middle }

} 

but this didn't do anything. could someone give me some pointers on how to do this please?

KexAri
  • 3,867
  • 6
  • 40
  • 80
  • possible duplicate of [How to make an image center (vertically & horizontally) inside a bigger div](http://stackoverflow.com/questions/388180/how-to-make-an-image-center-vertically-horizontally-inside-a-bigger-div) – Burak Arslan Apr 30 '15 at 16:25
  • I recently stumbled upon http://howtocenterincss.com/ which basically is a multiple choice site about centering in CSS :-) – Boris Apr 30 '15 at 16:25
  • This just isn't what vertical-align does. It really only aligns things in relation to a line of text, not the parent div http://phrogz.net/css/vertical-align/ – Matthew Apr 30 '15 at 16:34

2 Answers2

1

You could try the absolute positioning trick on the image itself:

.centeredImage img {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
}
<p class="centeredImage">
    <img src="http://placehold.it/150x100">
</p>
Marc Audet
  • 46,011
  • 11
  • 63
  • 83
1

Try this:

#img{      
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) 
}

Here's the jsfiddle.

Filipe Paulo
  • 134
  • 6
  • 1
    You can clean up the CSS, you don't need the padding and the margin-right properties, take them out and your technique works equally well. – Marc Audet Apr 30 '15 at 16:48