login-page:
login-form:
<body>
<div id="login-page" >
<div class="login-form">
</div>
</div>
</body>
#login-page {
border:1px solid blue;
}
.login-form {
border: 1px solid red;
width:200px;
height:250px;
margin: auto;
}
当子元素margin:auto时,其左右margin将会平分剩余“可用空间” ---> 因此,会出现“水平居中”现象。(子元素整体占用的是父元素的content部分,所以 子元素左右margin:(962-200-2)/2=380)
#login-page {
border:1px solid blue;
}
.login-form {
border: 1px solid red;
width:200px;
height:250px;
margin-left: auto; /*占用左侧全部可用空间*/
/* margin-right: auto;*/ /*占用右侧全部可用空间*/
}
.login-form a{
/*margin: auto;*/ /*不管用*/
margin-top: 50px; /*不管用*/
}
由于auto左右均匀占据可用空间,如果只设置其中一个时,则会出现左移/右移。
注意:以上属性设置方式,不适用于浮动和行内元素(如上图),且不能用于绝对和固定定位元素。
垂直居中
首先要设置该div元素祖先元素html、body的高度为100%(因为默认是0),并且要清除默认样式(即把margin、padding设置为0),如果不清除默认样式的话,浏览器会出现滚动条...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.content {
width: 300px;
height: 300px;
background: orange;
margin: 0 auto; /*水平居中*/
}
</style>
</head>
<body>
<div class="content"></div>
</body>
</html>
接下来就是要把div往下移,由于默认情况下,position的值是static(元素在文档流中是从上往下,从左往右紧密布局的),所以不能直接设置top、left等属性改变偏移量。所以,要想移动位置,则要先把position设置为不是static的其他值(relative、absolute、fixed),然后通过top、left、right、bottom等属性使其在文档中发生偏移。(注意:relative不会使元素脱离文档流,absolute和fixed会,也就是说,relative会占据移动之前的位置,但是absolute和fixed就不会)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.content {
width: 300px;
height: 300px;
background: orange;
margin: 0 auto; /*水平居中*/
position: relative; /*设置position属性*/
left:0;
right:0;
top:0;
bottom:0
}
</style>
</head>
<body>
<div class="content"></div>
</body>
</html>
备注:CSS3中弹性布局(flex)将很好的解决垂直居中问题。