margin方法
可以通过margin来使得div居中,通过给margin-left设置的值为父元素的宽减去子元素的宽再除以2(本例中:(400-100)/2=150px),margin-top的值为父元素的高度减去子元素的高度值再除以2(本例中:(300-100)/2=100px)
例:
<style>
.box{
width:400px;
height:300px;
border:1pxsolid#ccc;
}
.box1{
width:100px;
height:100px;
background-color:pink;
margin-left:150px;
margin-top:100px;
}
</style>
</head>
<body>
<div>
<div></div>
</div>
</body>
</html>
效果图:
position方法
可以通过定位的方法来使得div垂直居中,我们可以设置子元素绝对定位,另外设置top和left值为50%,但是需要注意一点在用定位是也要设置margin值,其中margin-left与margin-right的值都为负值,且值的大小是子元素宽高的一半
例:
<style>
.box{
width:400px;
height:300px;
border:1pxsolid#ccc;
position:relative;
}
.box1{
width:100px;
height:100px;
background-color:pink;
position:absolute;
top:50%;
left:50%;
margin:-50px00-50px
}
</style>
</head>
<body>
<divclass="box">
<divclass="box1"></div>
</div>
</body>
</html>

本文转载自中文网

本文转载自中文网
如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h55806.shtml