本文摘自PHP中文网,作者青灯夜游,侵删。

【推荐教程:CSS视频教程 】
我们一起来学习一下CSS 的Grid布局是如何使用的
通过这篇文章以后等我们自己做UI库的时候就会多了一种做法。
我们来使用CSS Grid创建一个超酷的图像网格图,它可以根据屏幕的宽度来改变列的数量。最精彩的地方在于:所有的响应特性被添加到了一行css代码中。这意味着我们不必将HTML与丑陋的类名(如col-sm-2, col-md-4)混杂在一起,也不必为每个屏幕创建媒体查询。

我们首先根据这个最基本的样式来分析grid,然后进行拓展。接下来我将代码分享给大家:
html代码:
1 2 3 4 5 6 7 8 | <div class = "container" >
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
|
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 | * {
margin : 0 ;
padding : 0 ;
}
// grid布局的关键代码!!!
// grid布局的关键代码!!!
// grid布局的关键代码!!!
.container {
display : grid;
grid-template-columns: 100px 100px 100px ;
grid-template-rows: 50px 50px ;
}
.container div {
text-align : center ;
line-height : 50px ;
border : 2px solid ;
margin : 2px ;
}
.container div:nth-child( 1 ) { background : yellow;}
.container div:nth-child( 2 ) { background : orange;}
.container div:nth-child( 3 ) { background : red ;}
.container div:nth-child( 4 ) { background : yellowgreen;}
.container div:nth-child( 5 ) { background : paleturquoise;}
.container div:nth-child( 6 ) { background : greenyellow;}
|
这时我们打开控制台来分析它:

发现每一个子元素的宽高都变成了96px * 46px。可是我们并没有给子元素设置宽高,那么这个是哪里来的呢?我们在回头看父元素的样式:
1 2 3 4 5 6 7 | .container {
display : grid;
grid-template-columns: 100px 100px 100px ;
grid-template-rows: 50px 50px ;
}
|
由于我们给子元素加了2px的边框,最后展现的96 * 64也就清楚了,grid布局还将容器下的所有子元素变成了box-sizing: border-box;怪异盒模型。如果您对于怪异盒模型不是很了解请自行百度,如果想了解更多的CSS,HTML知识请观看:https://blog.csdn.net/weixin_43606158/article/details/89811189
我们来论证一下我们刚刚所猜测的。
我们现在将容器的css样式改为这样:
1 2 3 4 5 | .container {
display : grid;
grid-template-columns: 100px 100px 200px 100px ;
grid-template-rows: 80px 50px 20px ;
}
|
效果图:

阅读剩余部分
相关阅读 >>
transform-origin属性怎么用
CSS3的文本阴影text-shadow属性应该如何使用
CSS3的default伪类选择器使用详解
html5/CSS3 网页加载进度条的实现,下载进度条等经典案例
CSS3 transition-duration属性怎么用
vs2010 如何支持CSS3
CSS3实现条状百分比效果
html5+CSS3实现无插件拖拽上传图片(支持预览与批量)的详情介绍
运用CSS3动画需要运用什么规则
border-image-slice属性怎么用
更多相关阅读请进入《CSS3》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » 浅谈CSS3 Grid网格布局(display: grid)的用法