CSS之Grid网格布局

148 阅读2分钟
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Grid</title>
</head>

<style type="text/css">
span {
  font-size: 2em;
}

#container{
  display: grid;
  grid-template-columns: 33.33% 33.33% 33.33%;
  grid-template-rows: 33.33% 33.33% 33.33%; 

/*设置列宽
下面几种写法都是等宽3列写法
grid-template-columns: repeat(3, 33.33%);
grid-template-columns: 1fr 1fr 1fr;
grid-template-columns:repeat(auto-fill, 100px);
grid-template-columns:repeat(3, 1fr);

设置行高
grid-template-rows: repeat(3, 33.33%); 
*/


/*设置行间距 列间距*/
grid-row-gap: 20px; 
grid-column-gap: 20px;

/*先行后列,并且尽可能紧密填满,尽量不出现空格
grid-auto-flow: row dense; 
*/

/*跟flex的用法差不多
justify-content: start | end | center | stretch | space-around | space-between | space-evenly;
align-content: start | end | center | stretch | space-around | space-between | space-evenly; 
(space-evenly - 项目与项目的间隔相等,项目与容器边框之间也是同样长度的间隔。)

place-self属性是align-self属性和justify-self属性的合并简写形式。
place-self: <align-self> <justify-self>;
place-self: center center;
*/
}

.item {
/*
grid-column-start:左边框所在的垂直网格线
grid-column-end:右边框所在的垂直网格线
grid-row-start:上边框所在的水平网格线
grid-row-end:下边框所在的水平网格线
grid-column属性是grid-column-start和grid-column-end的合并简写形式
grid-column: 1 / 3;
grid-column-start: 1;
grid-column-end: 3;
*/
  font-size: 2em;
  text-align: center;
  border: 1px solid #e5e4e9;
}

.item-1 {
  background-color: #ef342a;
}

.item-2 {
  background-color: #f68f26;
}

.item-3 {
  background-color: #4ba946;
}

.item-4 {
  background-color: #0376c2;
}

.item-5 {
  background-color: #c077af;
}

.item-6 {
  background-color: #f8d29d;
}

.item-7 {
  background-color: #b5a87f;
}

.item-8 {
  background-color: #d0e4a9;
}

.item-9 {
  background-color: #4dc7ec;
}
</style>

<body>

<span>foo</span>
<div id="container">
  <div class="item item-1">1</div>
  <div class="item item-2">2</div>
  <div class="item item-3">3</div>
  <div class="item item-4">4</div>
  <div class="item item-5">5</div>
  <div class="item item-6">6</div>
  <div class="item item-7">7</div>
  <div class="item item-8">8</div>
  <div class="item item-9">9</div>
</div>
<span>bar</span>

</body>
</html>