本文最后更新于:2020年12月9日 上午
背景
grid 可视化布局, css grid 完整指南
早就知道 css grid 布局非常强大,但之前由于兼容性问题一直没有机会尝试,近来在生产环境中大规模尝试使用它,并尝试在 react 中进行封装:在 react 中优雅的使用 grid 实现页面布局,于此记录一下各种常见布局的 grid 实现。
附:grid 真的是一个非常强大自适应布局系统。
示例
注:以下示例均默认引用了 Normalize.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
| <body> <style> html, body, .container { height: 100%; }
.container { display: grid; grid-template-columns: 300px 1fr; grid-template-rows: auto 1fr; grid-template-areas: "header header"; } .header { grid-area: header; } .container > * { border: solid 1px red; } </style> <div class="container"> <header class="header">header</header> <section>sidebar</section> <section>content</section> </div> </body>
|
中后台基本布局.html
纵向布局

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
| <body> <style> html, body, .container { height: 100%; }
.container { display: grid; /* 下面这行指定了 第一行按照内容自适应高度 第二行占有剩余高度 */ grid-template-rows: auto 1fr; }
.container > * { border: solid 1px red; } </style> <div class="container"> <header>header</header> <section>content</section> </div> </body>
|
纵向布局.html
模拟 flex margin-left 或 margin-right

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <body> <style> .container { display: grid; grid-template-columns: auto 1fr auto; justify-items: end; }
.container > * { border: solid 1px red; } </style> <header class="container"> <img src="https://picsum.photos/20" alt="logo" /> <div>用户名</div> <div>消息</div> </header> </body>
|
模拟 flex margin-left 或 margin-right.html
根据内容自适应贴靠在一边
如下图展示一个图片列表

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <body> <style> .container { display: grid; grid-template-columns: auto auto; justify-content: start; grid-gap: 8px; } </style> <section class="container"> <img src="https://picsum.photos/seed/1/100" /> <img src="https://picsum.photos/seed/2/100" /> <img src="https://picsum.photos/seed/3/100" /> <img src="https://picsum.photos/seed/4/100" /> <img src="https://picsum.photos/seed/5/100" /> <img src="https://picsum.photos/seed/6/100" /> </section> </body>
|
根据内容自适应贴靠在一边.html