1.垂直水平居中
<style>
/* 1. 基于定位 */
/* .content {
position: relative;
background-color: #ccc;
width: 500px;
height: 500px
} */
/* .box { 缺点:需要知道宽高以及精确计算
position: absolute;
background-color: #f00;
width: 50px;
height: 50px;
left: 50%;
top: 50%;
margin-left: -25px;
margin-top: -25px;
} */
/* .box { 缺点:需要知道宽高
position: absolute;
background-color: #f00;
width: 50px;
height: 50px;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
} */
/* .box 缺点:兼容性
position: absolute;
padding: 20px;
background-color: #f00;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
} */
/* 2.基于flex */
/* .content {
display: flex;
justify-content: center;
align-items: center;
width: 500px;
height: 500px;
background-color: #ccc;
}
.box {
padding: 20px;
background-color: #f00;
} */
/* 3.基于js */
/* 4.基于table-cell */
</style>
<body>
<div class="content">
<div class="box">css</div>
</div>
</body>
2.两栏、三栏布局
<style>
/* 使用margin实现两边固定,中间自适应 */
.content{
padding: 0 0 0 200px;
}
.right, .left {
width: 200px;
}
.center, .right, .left {
float: left;
box-sizing: border-box;
min-height: 300px;
}
.center {
width: 100%;
background: #ccc;
}
.left {
position: relative;
border: 1px solid #f00;
left: -100%;
margin-left: -200px;
}
.right {
border: 1px solid #ff0;
margin-right: -200px;
}
/* 使用flex实现两边固定,中间自适应 */
.content {
display: flex;
justify-content: space-between;
height: 100%;
}
.left, .right {
flex: 0 0 200px;
height: 300px;
border: 1px solid #f00;
}
.center {
flex: 1;
min-height: 300px;
border: 1px solid #ff0;
}
/* 使用定位实现两边固定,中间自适应 */
.content {
position: relative;
overflow: hidden;
}
.left,.right {
position: absolute;
top: 0;
width: 200px;
height: 300px;
border: 1px solid #f00;
}
.left {
left: 0;
}
.right {
right: 0;
}
.center {
margin: 0 200px;
min-height: 300px;
border: 1px solid #ff0;
}
/* 左边固定,右边自适应 */
.content {
padding: 0 0 0 200px;
}
.left, .right {
float: left;
box-sizing: border-box;
min-height: 300px;
}
.right{
width: 100%;
background: #ccc;
}
.left {
width: 200px;
border: 1px solid #f00;
position: relative;
left: -100%;
margin-left: -200px;
}
/* 右边固定,左边自适应 */
.content{
padding: 0 200px 0 0px;
}
.right {
width: 200px;
}
.center, .right {
float: left;
box-sizing: border-box;
min-height: 300px;
}
.center {
width: 100%;
background: #ccc;
}
.right {
border: 1px solid #ff0;
margin-right: -200px;
}
</style>
<body>
<!-- 使用margin、定位实现两边固定,中间自适应 -->
<div class="content">
<div class="center"></div>
<div class="left"></div>
<div class="right"></div>
</div>
<!-- 使用flex实现两边固定,中间自适应 -->
<div class="content">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
<!-- 左边固定,右边自适应 -->
<div class="content">
<div class="right"></div>
<div class="left"></div>
</div>
<!-- 右边固定,左边自适应 -->
<div class="content">
<div class="center"></div>
<div class="right"></div>
</div>
</body>