绝对定位和外边距
对元素开启绝对定位(包含块开启相对定位,否则是相对根元素)。
.box{
width:100px;
height:100px;
background-color:#bfa
position:absolute;
top:0;
left:0;
bottom:0;
right:0;
margin:auto;
}
缺点:要求元素的大小确定(有width和height),如果不设置,默认width和height撑开到整个页面。
Table cell和align
/*box1是box2的父元素*/
.box1{
width: 300px;
height: 300px;
background-color: orange;
display: table-cell;
vertical-align: middle;
/*对父元素开启table-cell和vertical-align,实现垂直居中*/
}
.box2{
width: 100px;
height: 100px;
background-color: #bfa;
margin: 0 auto;
/*对子元素开启margin,实现水平居中*/
/*由于text-align是对字使用的,故对父元素开启text-align:center是无效的,还得用margin*/
}
绝对定位和平移
先设置绝对定位来让元素(大致)位于页面中间,再平移自身的50%进行微调。
.box{
position:absolute;
left:50%;
top:50%
/*绝对定位*/
transform:translateX(-50%) translateY(-50%);
/*中间用空格隔开*/
}
弹性盒
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.box1{
width: 500px;
height: 500px;
margin: 50px auto;
border: 10px solid red;
/*关键在于以下三行*/
display: flex;
justify-content: center;
align-items: center;
}
.box2{
width: 100px;
height: 50px;
border: 5px solid green;
background-color: #bfa;
line-height: 50px;
text-align: center;
font-weight: bold;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2">子元素</div>
</div>
</body>
</html>
效果展示: