1.回字布局
首先可知父元素是定宽高,要求子元素垂直居中
仅居中元素定宽高适用
- absolute + 负margin(兼容性好)
- absolute + margin auto(兼容性好)
- absolute + calc(top: calc(50% - 50px); left: calc(50% - 50px),兼容性不好)
居中元素不定宽高
- absolute + transform( transform: translate(-50%, -50%),兼容性不好)
- lineheight(子元素必须是行内元素,兼容性好)
- css-table(父元素table-cell,子元素行内元素,兼容性好)
- flex(父元素display: flex; justify-content: center; align-items: center,兼容性不好)
- grid(父元素display: grid,子元素 align-self: center; justify-self: center,兼容性不好)
总结:
- PC端有兼容性要求,宽高固定,推荐absolute + 负margin
- PC端有兼容要求,宽高不固定,推荐css-table
- PC端无兼容性要求,推荐flex
- 移动端推荐使用flex
2.三栏布局,两侧定宽中间自适应
1)双飞燕布局
<!DOCTYPE html>
<html>
<head>
<title>双飞翼</title>
<style type="text/css">
html, body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
.left {
width: 100px;
background: red;
margin-left: -100%;
}
.right {
width: 200px;
background: green;
margin-left: -200px;
}
.main {
width: 100%;
background: blue;
background: #aaccdd;
}
.inner {
margin: 0 200px 0 100px;
}
.main, .left, .right {
float: left;
}
</style>
</head>
<body>
<div class="main">
<div class="inner">
main
</div>
</div>
<div class="left">
left
</div>
<div class="right">
right
</div>
</body>
</html>
特点:子元素3个float:left,左右使用margin-left使其达到在左右位置,中间自适应元素的子元素加左右margin
2)圣杯布局
<!DOCTYPE html>
<html>
<head>
<title>圣杯布局</title>
<style type="text/css">
html, body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
.container {
width: 100%;
height: 100%;
padding: 0 200px 0 100px;
overflow: hidden;
box-sizing: border-box;
}
.left {
width: 100px;
background: red;
margin-left: -100%;
left: -100px;
}
.right {
width: 200px;
background: green;
margin-left: -200px;
left: 200px;
}
.main {
width: 100%;
background: blue;
position: relative;
background: #aaccdd;
}
.main, .left, .right {
float: left;
position: relative;
}
</style>
</head>
<body>
<div class="container">
<div class="main">
main
</div>
<div class="left">
left
</div>
<div class="right">
right
</div>
</div>
</body>
</html>
特点:子元素3个float:left、position:relative,左右使用margin-left、left使其达到在左右位置,中间自适应元素宽度100%,父元素加padding留出两边位置
3.BFC
BFC全称是Block Formatting Context,即块格式化上下文。
4.盒模型
盒模型分为IE怪异盒模型和W3C标准盒模型
IE怪异盒模型:计算宽高时包含content+border+padding,css表现形式为box-sizing:border-box
W3C标准盒模型:计算宽高时只包含content+border+padding,css表现形式为box-sizing:content-box