如何讓div水平垂直居中
@(css)[妙瞳]
引子
我們經常遇到需要把div中的內容進行水平和垂直居中。所以,這里介紹一種方法,可以使div水平居中和垂直居中。
代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>div水平垂直居中</title>
<style>
*{
margin:0;
padding:0;
}
div.box{
background-color:pink;
border:2px solid #000;
width:960px;
height:500px;
margin-left:50px;
}
</style>
</head>
<body>
<div class="box">
<img src="girl.jpg" alt="美女">
</div>
</body>
</html>
效果圖:
現在先讓圖片在div中水平居中
我們可以先給圖片套一層盒子。
代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>div水平垂直居中</title>
<style type="text/css">
*{
margin:0;
padding:0;
}
div.container{
background-color:pink;
border:2px solid #000;
width:500px;
height:500px;
margin:50px auto;
display:table;
}
div.wrapper{
text-align:center;
display:table-cell;
vertical-align:middle;
}
div.wrapper img{
border:1px solid #ddd;
}
</style>
</head>
<body>
<div class="container">
<div class="wrapper">
<img src="girl.jpg" alt="美女"/>
</div>
</div>
</body>
</html>
IE8/Firefox/Chrome/Safari/Opera頁面效果:
IE6/IE7頁面效果:
由此可見要做IE6/IE7的兼容:
代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>div水平垂直居中</title>
<style type="text/css">
*{
margin:0;
padding:0;
}
div.container{
background-color:pink;
border:2px solid #000;
width:500px;
height:500px;
margin:0 auto;
display:table;
margin-top:20px;
}
div.wrapper{
text-align:center;
display:table-cell;
vertical-align:middle;
}
div.wrapper img{
border:1px solid #ddd;
}
</style>
<!--[if lte IE 7]>
<style type="text/css">
div.container{
position:relative;
}
div.wrapper{
position:absolute;
left:50%;top:50%;
}
div.wrapper img{
position:relative;
left:-50%;top:-50%;
}
</style>
<![endif]-->
</head>
<body>
<div class="container">
<div class="wrapper">
<img src="girl.jpg" alt="美女"/>
</div>
</div>
</body>
</html>
IE6/IE7效果圖:
綜上所述,要讓div里面的內容水平居中,可以使用text-align:center;
要實現垂直居中,container 的display:table;而wrapper的display:table-cell;同時vertical-align:middle;就可以實現div里的圖片水平垂直居中。
假如是多張圖片,要實現居中:
代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>div水平垂直居中</title>
<style>
*{
margin:0;
padding:0;
}
div.container{
background-color:pink;
border:2px solid #000;
width:700px;
height:500px;
margin:0 auto;
margin-top:50px;
}
div.wrapper{
text-align:center;
margin-top:28px;
}
div.wrapper img{
border:1px solid #ddd;
width:200px;
margin:10px;
}
</style>
</head>
<body>
<div class="container">
<div class="wrapper">
<img src="girl3.jpg" alt="美女"/>
<img src="girl3.jpg" alt="美女"/>
<img src="girl3.jpg" alt="美女"/>
<img src="girl3.jpg" alt="美女"/>
<img src="girl3.jpg" alt="美女"/>
<img src="girl3.jpg" alt="美女"/>
</div>
</div>
</body>
</html>
IE6/IE7/IE8/Firefox/Chrome/Safari/Opera頁面效果:
div.wrapper中的text-align:center;實現水平居中,margin-top:28px;實現垂直居中。
28px=[500-(200+1+1+10+10)*2]/2,即外層的高度減去里面的高度,然后除以2,設置margin-top,即可居中。
假如有錯誤或者建議的地方,歡迎指正!-----妙瞳。