4种方法实现css布局水平居中
方法一:margin + width
<!Doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK"/>
<title>css布局水平居中margin + width</title>
<style type="text/css">
*{margin:0;padding:0;}
.box{
width:100px;
margin:0 auto;
background:red;
}
</style>
</head>
<body>
<div class="box">Demo</div>
</body>
</html>
方法二:table + margin
<!Doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK"/>
<title>css布局水平居中table + margin</title>
<style type="text/css">
*{margin:0;padding:0;}
.box{
display: table;
margin: 0 auto;
background:red;
}
</style>
</head>
<body>
<div class="box">Demo</div>
</body>
</html>
说明:display: table在表现上类似block元素,但是宽度为内容宽。无需设置父元素样式 (支持 IE 8 及其以上版本)兼容 IE 8 一下版本需要调整为
方法三:inline-block + text-align
<!Doctype html>
<html><head> <meta http-equiv="Content-Type" content="text/html; charset=GBK"/> <title>css布局水平居中inline-block + text-align</title> <style type="text/css"> *{margin:0;padding:0;} .content{ text-align:center; } .box{ display:inline-block; background: red; } </style></head><body><div class="content"> <div class="box">Demo</div></div></body></html>
方法四:absolute + margin-left
<!Doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK"/>
<title>css布局水平居中absolute + margin-left</title>
<style type="text/css">
*{margin:0;padding:0;}
.content{
position: relative;
}
.box{
position: absolute;
left: 50%;
width: 100px;
margin-left: -50px;
background: red;
}
</style>
</head>
<body>
<div class="content">
<div class="box">Demo</div>
</div>
</body>
</html>
说明:宽度固定相比于使用transform ,有兼容性更好