Daily Archives: 二月 11, 2012

CSS HTML 前端

跨浏览器任意内容的水平垂直居中

IE6、7一日不死,被折腾的人就层出不穷。

以前只是想办法让图片在所有浏览器中在固定容器里水平垂直居中,现在遇到的则是要让一些内容(由图片、文字等组成)在固定容器中水平垂直居中。过程就不说了,以下提供的关键点就在table、display: inline-block上。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html>
    <head>
        <title>table vertical align</title>
        <style>
            #container {
                width: 400px;
                height: 400px;
                text-align: center;
                background-color: orange;
            }
            #wrapper {
                width: 100%;
                height: 100%;
                background-color: brown;
            }
            #content {
                display: inline-block;               
                *display: inline;
                *zoom: 1;
                text-align: left;
                background-color: green;
                color: white;
            }
        </style>
    </head>
    <body>
        <div id="container">
            <table id="wrapper">
                <tr>
                    <td>
                        <div id="content">
                            <h2>here is title</h2>
                            <span>here is additional message</span><br />
                            <a href="#">OK</a>
                        </div>
                    </td>
                </tr>
            </table>
        </div>
    </body>
</html>

#content所在部分可以替代为一张图片,这样可以实现对图片在固定容器里的水平垂直居中,而其他的复合内容则需要放置在#content中。