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

相关推荐
我是苏苏21 小时前
Web开发:C#通过ProcessStartInfo动态调用执行Python脚本
java·服务器·前端
无羡仙21 小时前
Vue插槽
前端·vue.js
用户6387994773051 天前
每组件(Per-Component)与集中式(Centralized)i18n
前端·javascript
SsunmdayKT1 天前
React + Ts eslint配置
前端
开始学java1 天前
useEffect 空依赖 + 定时器 = 闭包陷阱?count 永远停在 1 的坑我踩透了
前端
zerosrat1 天前
从零实现 React Native(2): 跨平台支持
前端·react native
狗哥哥1 天前
🔥 Vue 3 项目深度优化之旅:从 787KB 到极致性能
前端·vue.js
青莲8431 天前
RecyclerView 完全指南
android·前端·面试
青莲8431 天前
Android WebView 混合开发完整指南
android·前端·面试