1、传统的行内元素和块内元素在div中居中情况
<div style="text-align:center;border:1px red solid"> <p style="border:1px black solid">我是块级元素,我不居中</p> <span style="border:1px green solid">我是行内元素,我要居中</span> </div>
2、块内元素若设置宽度之后是不居中的,但是里面的文本居中
<div style="text-align:center;border:1px red solid; 600px;"> <p style="border:1px black solid; 400px;">我是块级元素,我不居中</p> <span style="border:1px green solid">我是行内元素,我要居中</span> </div>
3、ul元素在div块元素内居中
<style type="text/css"> .container{ text-align:center; border: 1px black solid; } .container ul{ margin: 10px; list-style:none; padding:10px; display:inline; } .container li{ margin-right:8px; border: 1px red solid; display:inline; } </style> </head> <body> <div class="container"> <ul> <li><a href="javascript:;">首页</a></li> <li><a href="javascript:;">菜单一</a></li> <li><a href="javascript:;">菜单二</a></li> <li><a href="javascript:;">菜单三</a></li> </ul> </div>
4、div定宽居中
<style type="text/css"> .container{ position: relative; width: 400px; height: 400px; border: 1px black solid; } .container div{ position: absolute; top: 50%; left:50%; margin-left: -25px; margin-top:-25px; width: 50px; height: 50px; background: #ccc; } </style> </head> <body> <div class="container"> <div>居中定位</div> </div>
5、div定宽居中
<style type="text/css"> .container{ position: relative; width: 400px; height: 400px; border: 1px black solid; } .container div{ margin: 0 auto; width: 200px; border: 1px red solid; } </style> </head> <body> <div class="container"> <div>自定义宽度的居中定位</div> </div>