这篇文章给大家分享的是CSS实现九宫格布局方法。千万别小瞧九宫格,下文介绍的实现九宫格布局小编觉得挺实用的,因此分享给大家做个参考,文中的示例代码介绍得很详细,有需要的朋友可以参考,接下来就跟随小编一起了解看看吧。
九宫格实现
下面几种实现方法都可自适应
基本布局和样式
<div class="box">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
</ul>
</div>
.box {
background: #e4f7fd61;
border: 2px solid #0786ada1;
border-radius: 8px;
}
ul {
padding: 0;
margin: 0;
}
.box li {
list-style: none;
text-align: center;
line-height: 200px;
background: skyblue;
border-radius: 8px;
font-size: 20px;
color: black;
}
实现一:flex
使用 flex 布局实现需要注意一个点,就是需要用 flex-wrap 属性来使其换行。
.box {
width: 100%;
overflow: hidden;
}
ul {
width: 100%;
height: 100%;
display: flex;
flex-wrap: wrap;
}
.box li {
width: 30%;
height: 30%;
margin-right: 5%;
margin-bottom: 5%;
}
.box li:nth-of-type(3n) {
margin-right: 0;
}
.box li:nth-of-type(n+7) {
margin-bottom: 0;
}
实现二:float
使用 float 来实现需要注意一个点,浮动会造成浮动崩塌,因此可以设置 overflow: hidden; 把 box 设置成 BFC 来解决浮动崩塌。
.box {
width: 100%;
overflow: hidden;
}
ul {
width: 100%;
height: 100%;
}
.box li {
width: 30%;
height: 30%;
margin-right: 5%;
margin-bottom: 5%;
float: left;
}
.box li:nth-of-type(3n) {
margin-right: 0;
}
.box li:nth-of-type(n+7) {
margin-bottom: 0;
}
实现三:grid
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
</div>
box {
background: #e4f7fd61;
border: 2px solid #0786ada1;
border-radius: 8px;
}
.grid {
display: grid;
width: 100%;
grid-template-rows: repeat(3, 1fr);
grid-template-columns: repeat(3, 1fr);
grid-gap: 5%;
grid-auto-flow: row;
}
.grid>div {
list-style: none;
text-align: center;
line-height: 200px;
background: skyblue;
border-radius: 8px;
font-size: 20px;
color: black;
}
实现四:table
使用表格来实现会存在一些缺陷,table 单元格之间的间隔是使用 border-spacing 属性来实现的,且不支持百分比的形式,而且单元格四周都有类似于 margin 的外边距的效果。
<div class="box">
<ul>
<li>
<div>1</div>
<div>2</div>
<div>3</div>
</li>
<li>
<div>4</div>
<div>5</div>
<div>6</div>
</li>
<li>
<div>7</div>
<div>8</div>
<div>9</div>
</li>
</ul>
</div>
.box {
width: 100%;
overflow: hidden;
}
ul {
width: 100%;
height: 100%;
display: table;
border-spacing: 10px;
}
.box li {
display: table-row;
}
.box li div {
display: table-cell;
text-align: center;
border-radius: 10px;
}
关于CSS实现九宫格布局方法就介绍到这,对大家学习CSS布局有一定的参考价值,希望大家阅读完这篇文章能有所收获。