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);

相关推荐
阿成学长_Cain9 分钟前
Linux telinit 命令详解:运行级别切换|关机重启|系统维护一站式掌握
linux·运维·前端·网络
Patrick_Wilson23 分钟前
最佳实践是有保质期的:从一次 CDN external 白屏事故说起
前端·性能优化·前端工程化
YHHLAI1 小时前
[特殊字符] Agent 智能体开发实战 · 第一课:Tool Use —— 让大模型自动干活
前端·人工智能
nuIl1 小时前
我把 5 个编码 Agent 塞进了一个 npm 包
前端·agent·claude
L-影1 小时前
FastAPI 静态文件:Web 页面的“固定展柜”与“加速引擎”
前端·fastapi
陪我去看海1 小时前
受够了 AI 写完代码留下一堆端口?我做了一个端口管理App!
前端·macos·vibecoding
Xuepoo1 小时前
我抛弃了 DOM,但保留了无障碍访问
前端
李明卫杭州1 小时前
Vue2 vs Vue3 的 h 函数:渲染函数完整迁移指南
前端
星栈1 小时前
LiveView 的认证系统:从登录到权限,我一开始以为有 `current_user` 就算完事了
前端·前端框架·elixir
在因斯坦1 小时前
摸摸鱼之前端自己研究 Jenkins 自动化部署
前端