左右布局
If two elements are displayed as a block:
html structure1
2
3
4<div class="wrapper clearFix">
<div class="red"></div>
<div class="blue"></div>
</div>
float方法
1 | css: |
flex布局
1 | .wrapper{ |
If two elements are displayed as an inline element:1
2
3
4
5
6
7
8
9
10
11
12
13.red{
width: 100px;
height: 50px;
display:inline-block;
background: red;
}
.blue{
width: 100px;
height: 50px;
display:inline-block;
background: blue;
}
左中右布局
html structure1
2
3
4
5<div class="wrapper clearFix">
<div class="red"></div>
<div class="blue"></div>
<div class="yellow"></div>
</div>
If two elements are displayed as a block:
float方法
1 | .clearFix:after{ |
flex布局
1 | .wrapper{ |
If two elements are displayed as a inline-element:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20.red{
width: 100px;
height: 50px;
display:inline-block;
background: red;
}
.blue{
width: 100px;
height: 50px;
display:inline-block;
background: blue;
}
.yellow{
width: 100px;
height: 50px;
display:inline-block;
background: yellow;
}
水平居中
inline元素的父元素上设置text-align:center;
1 | .wrapper{ |
div+css左右margin为auto(前提:已设置div的宽度)
1 | .wrapper{ |
绝对定位和margin-left:-(width/2);left:50%;
1 | .wrapper{ |
flex布局
1 | .wrapper{ |
或者1
2
3
4
5
6
7
8
9
10.wrapper{
display:flex;
flex-direction:column;
}
.red{
width: 100px;
height: 50px;
background: red;
margin:0 auto;
}
垂直居中
绝对定位和margin-top:-(height/2);top:50%;
缺点:需要事先知道div的尺寸(高度)1
2
3
4
5
6
7
8
9
10
11
12
13
14.wrapper{
width:100%;
height:300px;
position: relative;
background:#fff;
}
.red{
width: 50%;
height: 150px;
background: red;
position: absolute;
top:50%;
margin-top:-75px;
}
绝对定位和margin:auto;
1 | .wrapper{ |
flex布局
注意:flex-direction默认属性是row1
2
3
4
5
6
7
8
9
10
11
12
13.wrapper{
width:100%;
height:300px;
display:flex;
background:#fff;
align-items:center;
flex-direction:row;
}
.red{
width: 50%;
height: 150px;
background: red;
}
inline元素line-height=元素高度
此方法在inline-height较大时有bug1
2
3html structure:
<div class="wrapper clearFix">
<div class="red">123</div>
1 | .wrapper{ |
其他小技巧
画三角形
1 | .triangle1{ |
1 | .triangle2{ |