1css定位
<style>
.wrap {
position: relative;
background: #333;
height: 300px;
width: 300px;
}
.box {
position: absolute;
top: 50%;
left: 50%;
background: #999;
width: 100px;
height: 100px;
margin: -50px 0 0 -50px;
}
</style>
</head>
<body>
<div class="wrap">
<div class="box">
</div>
</div>
</body>

image.png
適用于父容器和子容器的寬高是確定的。
2.transition
<style>
.wrap {
position: relative;
background: #333;
height: 300px;
width: 300px;
}
.box {
position: absolute;
top: 50%;
left: 50%;
background: #999;
width: 100px;
height: 100px;
transform: translate(-50%, -50%)
}
</style>
</head>
<body>
<div class="wrap">
<div class="box">
</div>
</div>
</body>

image.png
利用c3的動(dòng)畫屬性
3.強(qiáng)大的flex
<style>
.wrap {
position: relative;
background: #333;
height: 300px;
width: 300px;
display: flex;
justify-content: center;
align-items: center;
}
.box {
background: #999;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div class="wrap">
<div class="box">
</div>
</div>
</body>

image.png
定義父容器為flex容器,添加設(shè)置主軸和次主軸居中 justify-content: center; align-items: center;代碼簡(jiǎn)潔優(yōu)雅
4.設(shè)置table的屬性,模擬表格定位
<style>
.table {
display: table;
height: 300px;
background: #aaa;
}
.cell {
display: table-cell;
width: 300px;
background: #999;
vertical-align: middle;
text-align: center;
}
.img {
width: 100px;
height: 100px;
background: #333;
display: inline-block;
}
</style>
</head>
<body>
<div class="table">
<div class="cell">
<div class="img">
</div>
</div>
</div>
</body>
頁(yè)面看成一個(gè)表格的思想,也很不錯(cuò)
用table完成一個(gè)兩邊固定,中間自適應(yīng)(圖片居中)的經(jīng)典布局:
<style>
.table {
display: table;
width: 100%;
background: #aaa;
}
.cell {
display: table-cell;
/* background: #999; */
vertical-align: middle;
text-align: center;
}
.table .left,.table .right {
width: 300px;
height: 300px;
background: burlywood;
}
.img {
width: 100px;
height: 100px;
background: #333;
display: inline-block;
}
</style>
</head>
<body>
<div class="table">
<div class="cell left"></div>
<div class="cell">
<div class="img">
</div>
</div>
<div class="cell right"></div>
</div>
</body>

image.png