上下固定,中间自适应 左右固定,中间自适应 一侧固定,另一侧自适应
1.上下固定,中部自适应布局 1. 绝对定位实现
原理:让中部绝对定位撑开剩余空间,此时中部会遮挡底部,所以也需要给上下设置为绝对定位。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 body { padding : 0 ; margin : 0 ; } header { position : absolute; top : 0 ; width : 100% ; height : 100px ; background-color : yellow; } main { position : absolute; top : 100px ; bottom : 100px ; width : 100% ; background-color : pink; } footer { position : absolute; bottom : 0 ; height : 100px ; width : 100% ; background-color : gray; }
2. flex的grow实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 html ,body { height : 100% ; } body { display : flex; flex-direction : column; margin : 0 ; padding : 0 ; } header { height : 100px ; background-color : yellow; } main { flex-grow : 1 ; background-color : pink; } footer { height : 100px ; background-color : gray; }
2.左固定,右自适应,两栏布局 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 body { padding : 0 ; margin : 0 ; } .left { float : left; width : 200px ; height : 500px ; background-color : pink; } .right { height : 500px ; margin-left : 200px ; background-color : yellow; }
3.左右固定,中间自适应,三栏布局 方法一,左中右绝对定位,左left:0
,右right:0
,中间设置left
和right
撑开剩余空间,宽度默认填充。
方法二,同上绝对定位,不同的地方在于,中间不使用绝对定位,使用margin
代替left
和right
。
方法三,flex布局,左右宽度固定,中间设置flex-grow:1;
方法四,浮动布局,左右宽度固定,左设置左浮动,右设置右浮动,中间正常只设置左右margin
。需要注意,中间的 HTML 要写在最后,原因是如果在中间则会导致右浮动元素在下一行右浮动,只有先让浮动元素脱离文档流,使得最后写的中间元素上移,被浮动元素覆盖。浮动只会影响当前的或者是后面的标准流盒子,不会影响前面的标准流。
4.圣杯、双飞翼布局 圣杯、双飞翼布局的特点体现在html的结构上,css只是对元素进行相应调整,或用到上面提到的方法,来达到自适应布局。
5.实现宽高自适应的正方形 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 .square { width : 10% ; height : 10vw ; background : tomato; } .square { width : 20% ; height : 0 ; padding-top : 20% ; background : orange; } .square { width : 30% ; overflow : hidden; background : yellow; } .square ::after { content : '' ; display : block; margin-top : 100% ; }