设置上下padding相等实现居中
这种设置简单粗暴
代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JS Bin</title> <style> .ct{ padding: 50px 0px; text-align: center; background: #eee; } </style> </head> <body> <div class="ct"> <p>padding设置居中</p> <p>padding设置居中</p> </div> </body> </html>
效果:
绝对定位实现居中
绝对定位的设置适用于弹窗一类,但是会脱离文档流。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
html,body {
height: 100%;
}
.dialog {
position: absolute;
left: 50%;
top: 50%;
margin-left: -200px;
margin-top: -150px;
width: 400px;
height: 300px;
box-shadow: 0px 0px 3px #000;
}
.dialog .header{
padding: 10px;
background: #000;
color: #fff;
}
.dialog .content{
padding: 10px;
}
</style>
</head>
<body>
<div class="dialog">
<div class="header">我是标题</div>
<div class="content">我是内容</div>
</div>
</body>
</html>
效果:
vertical-align实现居中
vertical-align作用在行内元素和表格上。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
.box{
width: 300px;
height: 500px;
border: 1px solid ;
text-align: center;
}
.box:before{
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.box img{
vertical-align: middle;
}
</style>
</head>
<body>
<div class="box">
<img src="http://img.hb.aicdn.com/844cc8626177f5429032aae7e5f42d0aa05b57a23437-8MCz1J_fw658" alt="">
</div>
</body>
</html>
效果:
使用table-cell实现居中
display:table-cell属性指让标签元素以表格单元格的形式呈现,类似于td标签。目前IE8+以及其他现代浏览器都是支持此属性的,但是IE6/7不支持,这一事实也是大大制约了display:table-cell属性在实际项目中的应用。
table-cell同样会被其他一些CSS属性破坏,例如float, position:absolute,所以,在使用display:table-cell与float:left或是position:absolute属性尽量不用同用。设置了display:table-cell的元素对宽度高度敏感,对margin值无反应,响应padding属性,基本上就是活脱脱的一个td标签元素了。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
.box{
width: 500px;
height: 500px;
border: 1px solid ;
display: table-cell;
vertical-align: middle;
text-align: center;
}
</style>
</head>
<body>
<div class="box">
<img src="http://img.hb.aicdn.com/844cc8626177f5429032aae7e5f42d0aa05b57a23437-8MCz1J_fw658" alt="">
</div>
</body>
</html>
效果: