In the era of making a webpage layout using table, it is very easy to center an image of an unknown height vertically. The valign attribute of the cell tag TD can easily achieve this effect. However, in the layout of Div + CSS, this problem becomes tricky.
CSS:
Div {width: 300px; Height: 300px; line-Height: 300px; Vertical-align: middle; Border: 1px solid red ;}
IMG {width: 50px; Height: 50px; Vertical-align: middle ;}
HTML:
<Div> </Div>
In the above Code, we put an image with a width and height of 50 pixels (less than the container height) into a square container with a side length of 300 pixels and A Row Height of 300 pixels. As you may know, you can use vertical-align: middle to vertically center text by setting a line height (Ling-height) consistent with the height (height) for block-level elements, however, the image is still in the upper left corner of the container.
It seems that setting the line height and vertical alignment does not work. The following is a common implementation method:
CSS:
Div {width: 300px; Height: 300px; line-Height: 300px; Vertical-align: middle; Border: 1px solid red;Display: Table-cell; * display: block; * font-size: 263px;}
IMG {width: 50px; Height: 50px; Vertical-align: middle ;}
HTML:
<Div> </Div>
Display: Table-CellThe property allows the DIV container to be displayed as a table cell, but IE6/7 does not support table-cell, so here we use two exclusive CSS hack for IE,* Display: block; * font-size: 263px. The key to this solution is* Font-size: 263px. ie can be vertically centered when the ratio of height to font-size is about 1.14.