Method 1:
This method sets the display mode of the external container to display: table, the img label is nested with a span label, and the display mode of the span is set to display: table-cell, in this way, we can easily use vertical-align to align like table elements. Of course, this is only because IE6/IE7 still needs to be positioned in a standard browser.
HTML structure:
The code is as follows: |
Copy code |
<Div id = "box"> & Nbsp; <span> </span> </Div> |
CSS style section:
The code is as follows: |
Copy code |
<Style type = "text/css"> plain # Box { Width: 500px; height: 400px; Display: table; Text-align: center; Border: 1px solid # d3d3d3; background: # fff; } # Box span { Display: table-cell; Vertical-align: middle; } # Box img { Border: 1px solid # ccc; } </Style> <! -- [If lte IE 7]> <Style type = "text/css"> plain # Box { Position: relative; Overflow: hidden; } # Box span { Position: absolute; Left: 50%; top: 50%; } # Box img { Position: relative; Left:-50%; top:-50%; } </Style> <! [Endif] -->
|
Method 2:
The standard browser still sets the display mode of the external container # box to display: table-cell. IE6/IE7 inserts an empty label before the img label.
HTML structure:
The code is as follows: |
Copy code |
<Div id = "box"> & Nbsp; <I> </I> </Div> alert <Style type = "text/css"> plain # Box { Width: 500px; height: 400px; Display: table-cell; Text-align: center; Vertical-align: middle; Border: 1px solid # d3d3d3; background: # fff; } # Box img { Border: 1px solid # ccc; } </Style> <! -- [If IE]> <Style type = "text/css"> plain # Box I { Display: inline-block; Height: 100%; Vertical-align: middle } # Box img { Vertical-align: middle } </Style> <! [Endif] --> |
Method 3:
For IE6/IE7, this method sets the font size of the image external container to 0.873 times the height to achieve Center. The standard browser still uses the above method for compatibility, the structure is also elegant.
HTML structure:
The code is as follows: |
Copy code |
<Div id = "box"> & Nbsp; </Div>
|
CSS style section:
The code is as follows: |
Copy code |
# Box { Width: 500px; height: 400px; Text-align: center; Border: 1px solid # d3d3d3; background: # fff; /* Compatible with standard browsers */ Display: table-cell; Vertical-align: middle; /* Compatible with IE6/IE7 */ * Display: block; * Font-size: 349px;/* the font size is about 0.873 times of the container height, 400*0.873 = 349 */ * Font-family: Arial;/* prevents hack failures caused by non-UTF-8, such as gbk encoding */ } # Box img { Vertical-align: middle; } |