5

I am trying to vertically align/center some images within a div. It`s not 100% correct. The images are some pixels too much down to be vertically centered. Why is that?

.Container
{   
    width:280px;
    position:fixed;
    border:1px solid blue;
    left:0px;
    text-align: center;
    line-height:84px;
}

.Container input[type=image]
{
   vertical-align:middle;
}

UPDATE:

http://jsfiddle.net/2j531q32/

update 2: The images are not valid int the js fiddle There you see the gap between the image and the top border.

Clay Nichols
  • 11,848
  • 30
  • 109
  • 170
Elisabeth
  • 20,496
  • 52
  • 200
  • 321

4 Answers4

2

The accepted solution didn't work for me in IE11.

I found a great page of Method for Vertical Centering.

This works for me in Chrome and IE11 The line-height needs to be > the highest element to be centered.

#Parent{
    line-height: 200px; // > the highest element to be centered.
}

.parent img {
    vertical-align: middle;
}

Jsfiddle demonstration

Clay Nichols
  • 11,848
  • 30
  • 109
  • 170
1

No need for any line height css. You can vertically align divs using the display:table and display:table-cell styles. The height of .ButtonBarDiv has been exaggerated to show that they both center vertically.

One image per line: http://jsfiddle.net/eY7Ms/16/

Images on the same line: http://jsfiddle.net/eY7Ms/14/

Omega
  • 2,998
  • 2
  • 16
  • 19
0

After some research i found another question on stackoverflow: Image inside div has extra space below the image

It seems like browsers render an extra space above / below a line, so you might want to ajust the line-height, here is an exmaple:

http://jsfiddle.net/eY7Ms/13/

so if you want to adjust the vertical extra space, you might do something like that:

.boxWithVerticalCenteredContent {
    height: 4em;
    line-height: 3.6em;
}

i know, this is not perfectly centered and it is fixed in height, but if you want to center it absolute, you might want to use position: absolute and top, bottom, left, right

Community
  • 1
  • 1
r3bel
  • 1,350
  • 8
  • 12
0

Will only work in modern browsers but:

.elementToAlign{
position: relative;
top: 50%;
transform : translateY(-50%);
}
scottdavidwalker
  • 1,118
  • 1
  • 12
  • 30