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>
适用于父容器和子容器的宽高是确定的。
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>
利用c3的动画属性
3.强大的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>
定义父容器为flex容器,添加设置主轴和次主轴居中 justify-content: center; align-items: center;代码简洁优雅
4.设置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>
页面看成一个表格的思想,也很不错
用table完成一个两边固定,中间自适应(图片居中)的经典布局:
<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>