CSS实现DIV水平自适应居中

DIV水平自适应居中

 <!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="utf-8"/>
<title>如何自适应宽度的水平居中</title>
<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>
</head>
<body>
<div id="body">
<h2>水平居中 <code>display:inline-block</code></h2>
<div class="navbar center-1">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/">About us</a></li>
<li><a href="/">Our products</a></li>
<li><a href="/">Customer support</a></li>
<li><a href="/">Contact</a></li>
</ul>
</div>
<h2>水平居中 <code>position:relative</code></h2>
<div class="navbar center-2">
<div>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/">About us</a></li>
<li><a href="/">Our products</a></li>
<li><a href="/">Customer support</a></li>
<li><a href="/">Contact</a></li>
</ul>
</div>
</div>
<h2>水平居中 <code>display:table</code></h2>
<ul class="navbar center-3">
<li><a href="/">Home</a></li>
<li><a href="/">About us</a></li>
<li><a href="/">Our products</a></li>
<li><a href="/">Customer support</a></li>
<li><a href="/">Contact</a></li>
</ul>
<h2>水平居中 <code>display:inline-flex</code></h2>
<div class="navbar center-4">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/">About us</a></li>
<li><a href="/">Our products</a></li>
<li><a href="/">Customer support</a></li>
<li><a href="/">Contact</a></li>
</ul>
</div>
<h2>水平居中 <code> fit-content</code></h2>
<div class="navbar center">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/">About us</a></li>
<li><a href="/">Our products</a></li>
<li><a href="/">Customer support</a></li>
<li><a href="/">Contact</a></li>
</ul>
</div>
</div>
</body>
</html>
上一篇:C/C++中调用python文件


下一篇:在css嵌套中的html的table里的字左右不对齐