CSS实现九宫格布局(自适应)的示例代码
脚本之家
简介
本文用示例介绍CSS进行九宫格布局的方法。
朋友圈、微博等很多社交平台都是使用九宫格布局来展示图片的,九宫格布局也是前端面试经常会问的问题。
本文只展示自适应布局的方案。不展示手动指定宽度的那种方案。
方案1:grid
grid是专门用来处理二维的,最适合用来二维布局。
代码
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>This is title</title> <style> .container { display: grid; grid-template-columns: 1fr 1fr 1fr; grid-template-rows: 100px 100px 100px; grid-gap: 10px; padding: 10px; } .item { border: 1px solid black; </style> </head> <body> <div class="container"> <div class="item">1</div> <div class="item">2</div> <div class="item">3</div> <div class="item">4</div> <div class="item">5</div> <div class="item">6</div> <div class="item">7</div> <div class="item">8</div> <div class="item">9</div> </div> </body> </html>
结果
方案2:flex+calc()
因为flex是面向一维的,所以我们需要加上calc这个函数控制其垂直方向。
代码
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>This is title</title> <style> .container { width: 100%; display: flex; /*换行*/ flex-wrap: wrap; } .item { width: calc(calc(100% / 3) - 10px); height: 100px; margin: 5px; box-sizing: border-box; border: 1px solid black; </style> </head> <body> <div class="container"> <div class="item">1</div> <div class="item">2</div> <div class="item">3</div> <div class="item">4</div> <div class="item">5</div> <div class="item">6</div> <div class="item">7</div> <div class="item">8</div> <div class="item">9</div> </div> </body> </html>
结果
方案3:absolute
代码
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>This is title</title> <style> html,body{ height:100%; margin:0; } .container{ position:absolute; left:0; top:0; right:0; bottom:0; .item{ float:left; height:100px; width: calc(calc(100% / 3) - 10px); position:relative; border: 1px solid black; .item:before{ content:''; left:10px; right:10px; top:10px; bottom:10px; border-radius:10px; .item:after{ content:attr(data-index); height:30px; margin:auto; text-align:center; </style> </head> <body> <div class="container"> <div class="item" data-index="1"> </div> <div class="item" data-index="2"> <div class="item" data-index="3"> <div class="item" data-index="4"> <div class="item" data-index="5"> <div class="item" data-index="6"> <div class="item" data-index="7"> <div class="item" data-index="8"> <div class="item" data-index="9"> </div> </body> </html>
结果
到此这篇关于CSS实现九宫格布局(自适应)的示例教程的文章就介绍到这了,更多相关css九宫格布局内容请搜索脚本之家以前的文章或继续浏览下面的相关文章,希望大家以后多多支持脚本之家!