CSS:九宫格布局

九宫格布局效果如下:

HTML 结构:

html 复制代码
<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>

公共 CSS:

css 复制代码
.container {
  width: 310px;
}

.item {
  text-align: center;			
  line-height: 100px;
  vertical-align: middle;		/*文字水平垂直居中 */
  width: 100px;
  height: 100px;
  background-color: orange;
}

方法一:float

css 复制代码
.container {
  overflow: auto;		/*形成BFC以解决父元素高度塌陷 */ 
}

.item {
  float: left;
  margin-right: 5px;
  margin-bottom: 5px;
}
.item:nth-of-type(3n) {			/*最后一列 */			
  margin-right: 0;
}
.item:nth-of-type(n+7) {		/*最后一行 */
  margin-bottom: 0;
}

方法二:flex

css 复制代码
.container {
  display: flex;
  flex-wrap: wrap;		/*换行 */
}
.item {
  margin-right: 5px;
  margin-bottom: 5px;
}
.item:nth-of-type(3n) {					
  margin-right: 0;
}
.item:nth-of-type(n+7) {
  margin-bottom: 0;
}

如果容器和子项的宽都不固定,可以设置 item 样式为 { width: 30%; margin-right: 5%; }

如果子项之前间距固定,可以设置 item 样式为 { width: calc(calc(100% -10px) / 3); margin-right: 5px; }

方法三:grid

css 复制代码
.container {
  display: grid;
  grid-template-columns: repeat(3, 100px);
  grid-template-rows: repeat(3, 100px);
  grid-gap: 5px;
}

gird 布局不需要额外设置子项的宽高和外边距,如果想要自适应,可以设置 grid-template-columns: repeat(3, 1fr);

相关推荐
脱离语言16 分钟前
Jeecg3.8.2 前端经验汇总
开发语言·前端·javascript
NEXT0633 分钟前
useMemo 与 useCallback 的原理与最佳实践
前端·javascript·react.js
小爱丨同学34 分钟前
React-Context用法汇总 +注意点
前端·javascript·react.js
徐同保2 小时前
python如何手动抛出异常
java·前端·python
极客小云2 小时前
【实时更新 | 2026年国内可用的npm镜像源/加速器配置大全(附测速方法)】
前端·npm·node.js
半兽先生2 小时前
告别 AI 乱写 Vue!用 vue-skills 构建前端智能编码标准
前端·vue.js·人工智能
前端达人3 小时前
都2026年了,还在用Options API?Vue组合式API才是你该掌握的“正确姿势“
前端·javascript·vue.js·前端框架·ecmascript
Dxy12393102163 小时前
Python检查JSON格式错误的多种方法
前端·python·json
chao-Cyril4 小时前
从入门到进阶:前端开发的成长之路与实战感悟
前端·javascript·vue.js
shalou29014 小时前
Spring 核心技术解析【纯干货版】- Ⅶ:Spring 切面编程模块 Spring-Instrument 模块精讲
前端·数据库·spring