Vertical center of an unknown height image

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.