如上图,在日常开发中我们可能会遇到对页面进行不同布局配置的需求,实现方法也有很多,例如:
1.写多个页面,不同布局拥有不同的页面模板与样式代码,这种方法看起来是最麻烦也最没必要的,而且布局一但多起来编码会变得十分难受且冗余难以维护,特别当业务代码基本一致时,修改时也会变得繁琐,修改一种布局中的业务代码也要考虑到其他布局,显然这种方式是极其不推荐的。
2.写一个页面,页面内编写多套模板,通过条件控制实现不同布局风格。这种方法相比方法1的好处是使得业务代码可以在一处地方编写,并且相同的部分也只需编写一次,后期业务代码维护起来也变得更加容易。当然,方法1也可以通过引入外部文件实现同一套业务代码。然而这种方法问题在于模板跟样式都要编写几套,如果能只控制模板或只控制样式就可以实现的话无疑是更佳的方案。方法3将详细介绍通过grid布局方法编写一套模板多种样式实现布局布局风格控制。
3.写一个页面,通过grid布局将页面划分为合适的网格单元,即根据多种布局风格统一起来选择一个合适的行列分割数量。
页面模板,按照各种布局中网格数最多的编写(即4个)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <div> <div class= "wrap-layout1" > </div> <div class= "wrap-layout2" > </div> <div class= "wrap-layout3" > </div> <div class= "wrap-layout4" > </div> </div> |
将页面划分为12行12列共144个网格单元
css样式中编写不同布局的行列划分原则
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | .page- wrap { // width : 1920px ; // height : 1080px ; width : 100% ; height : 100% ; display : grid; grid-gap: 1px 1px ; grid-template-columns : repeat ( 12 , 8.333333% ); grid-template-rows : repeat ( 12 , 8.333333% ); position : relative ; background : #FFFFFF ; } .wrap-layout 1 , .wrap-layout 2 , .wrap-layout 3 , .wrap-layout 4 { background : #D8D8D8 ; } // 默认布局 .layout- default { .wrap-layout 1 { grid-column : 1 / 13 ; grid-row : 1 / 13 ; } .wrap-layout 2 , .wrap-layout 3 , .wrap-layout 4 { display : none ; } } // 布局一 .layout 1 { .wrap-layout 1 { grid-column : 1 / 9 ; grid-row : 1 / 13 ; } .wrap-layout 2 { grid-column : 9 / 13 ; grid-row : 1 / 5 ; } .wrap-layout 3 { grid-column : 9 / 13 ; grid-row : 5 / 9 ; } .wrap-layout 4 { grid-column : 9 / 13 ; grid-row : 9 / 13 ; } } // 布局二 .layout 2 { .wrap-layout 1 { grid-column : 1 / 3 ; grid-row : 1 / 13 ; } .wrap-layout 2 { grid-column : 3 / 11 ; grid-row : 1 / 13 ; } .wrap-layout 3 { grid-column : 11 / 13 ; grid-row : 1 / 13 ; } .wrap-layout 4 { display : none ; } } // 布局三 .layout 3 { .wrap-layout 1 { grid-column : 1 / 13 ; grid-row : 1 / 3 ; } .wrap-layout 2 { grid-column : 1 / 13 ; grid-row : 3 / 13 ; } .wrap-layout 3 { display : none ; } .wrap-layout 4 { display : none ; } } // 布局四 .layout 4 { .wrap-layout 1 { grid-column : 1 / 7 ; grid-row : 1 / 7 ; } .wrap-layout 2 { grid-column : 7 / 13 ; grid-row : 1 / 7 ; } .wrap-layout 3 { grid-column : 1 / 7 ; grid-row : 7 / 13 ; } .wrap-layout 4 { grid-column : 7 / 13 ; grid-row : 7 / 13 ; } } |
到此这篇关于CSS中使用grid布局实现一套模板多种布局的文章就介绍到这了,更多相关css grid布局内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章,希望大家以后多多支持IT俱乐部!