小围脖

Try , Try , Never Say Die !

 

CSS实现DIV水平自适应居中

DIV水平自适应居中

 1 <!DOCTYPE html>
 2 <html lang="cn">
 3 <head>
 4 <meta charset="utf-8"/>
 5 <title>如何自适应宽度的水平居中</title>
 6 <style>.navbar{margin:20px 0;}.navbar ul{margin:0;padding:20px;list-style:none;border-radius:8px;background:#eee;box-shadow:0 0 2px rgba(0,0,0,0.4) inset;}.navbar li{margin:0;padding:0;}.navbar a{display:block;padding:6px 10px;border-radius:12px;color:#111;background:#ccc;font:bold 1em/1 Arial,Helvetica,sans-serif;text-decoration:none;}.navbar a:hover,.navbar a:focus{color:#fff;background:#333;}.center-1{text-align:center;}.center-1 ul{display:inline-block;}.center-1 li{float:left;}.center-1 li+li{margin-left:20px;}.center-2{overflow:hidden;}.center-2>div{position:relative;left:50%;float:left;}.center-2 ul{position:relative;left:-50%;float:left;}.center-2 li{float:left;}.center-2 li+li{margin-left:20px;}.center-3{display:table;margin:20px auto;padding:20px;list-style:none;border-radius:8px;background:#eee;box-shadow:0 0 2px rgba(0,0,0,0.4) inset;}.center-3 li{display:table-cell;}.center-3 li+li{padding-left:20px;}.center-4{text-align:center;}.center-4>ul{display:-webkit-inline-box;display:-moz-inline-box;display:-ms-inline-flexbox;display:-webkit-inline-flex;display:inline-flex;}.center-4 li+li{margin-left:20px;}.ggsd{width:728px;margin:0 auto;}</style>
 7 </head>
 8 <body>
 9 <div id="body">
10 <h2>水平居中 <code>display:inline-block</code></h2>
11 <div class="navbar center-1">
12 <ul>
13 <li><a href="/">Home</a></li>
14 <li><a href="/">About us</a></li>
15 <li><a href="/">Our products</a></li>
16 <li><a href="/">Customer support</a></li>
17 <li><a href="/">Contact</a></li>
18 </ul>
19 </div>
20 <h2>水平居中 <code>position:relative</code></h2>
21 <div class="navbar center-2">
22 <div>
23 <ul>
24 <li><a href="/">Home</a></li>
25 <li><a href="/">About us</a></li>
26 <li><a href="/">Our products</a></li>
27 <li><a href="/">Customer support</a></li>
28 <li><a href="/">Contact</a></li>
29 </ul>
30 </div>
31 </div>
32 <h2>水平居中 <code>display:table</code></h2>
33 <ul class="navbar center-3">
34 <li><a href="/">Home</a></li>
35 <li><a href="/">About us</a></li>
36 <li><a href="/">Our products</a></li>
37 <li><a href="/">Customer support</a></li>
38 <li><a href="/">Contact</a></li>
39 </ul>
40 <h2>水平居中 <code>display:inline-flex</code></h2>
41 <div class="navbar center-4">
42 <ul>
43 <li><a href="/">Home</a></li>
44 <li><a href="/">About us</a></li>
45 <li><a href="/">Our products</a></li>
46 <li><a href="/">Customer support</a></li>
47 <li><a href="/">Contact</a></li>
48 </ul>
49 </div>
50 <h2>水平居中 <code> fit-content</code></h2>
51 <div class="navbar center">
52 <ul>
53 <li><a href="/">Home</a></li>
54 <li><a href="/">About us</a></li>
55 <li><a href="/">Our products</a></li>
56 <li><a href="/">Customer support</a></li>
57 <li><a href="/">Contact</a></li>
58 </ul>
59 </div>
60 </div>
61 </body>
62 </html>

 

posted on 2015-08-23 10:48  小围脖  阅读(2019)  评论(0编辑  收藏  举报

导航