CSS:九宫格布局

九宫格布局效果如下:
在这里插入图片描述
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:

.container {
   
  width: 310px;
}

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

方法一:float

.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

.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

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

相关推荐

  1. 微信小程序九宫布局,轮播图

    2024-02-08 06:56:01       64 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-08 06:56:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-08 06:56:01       101 阅读
  3. 在Django里面运行非项目文件

    2024-02-08 06:56:01       82 阅读
  4. Python语言-面向对象

    2024-02-08 06:56:01       91 阅读

热门阅读

  1. 设计模式(前端)

    2024-02-08 06:56:01       43 阅读
  2. Android 自定义BaseFragment

    2024-02-08 06:56:01       47 阅读
  3. k8s弃用docker后使用ctr导入镜像

    2024-02-08 06:56:01       44 阅读
  4. CGAL::2D Arrangements-4

    2024-02-08 06:56:01       55 阅读
  5. 后端的技术设计文档

    2024-02-08 06:56:01       45 阅读
  6. 能源管理师——为能源可持续发展护航

    2024-02-08 06:56:01       53 阅读
  7. Android:Intent&Activity,Service,BroadcastReceiver

    2024-02-08 06:56:01       52 阅读
  8. Days 24 Elfboard 读取摄像头视频进行目标检测

    2024-02-08 06:56:01       46 阅读
  9. 机器学习如何改变缺陷检测的格局?

    2024-02-08 06:56:01       52 阅读
  10. UMLChina公众号精选(20240207更新)

    2024-02-08 06:56:01       40 阅读
  11. 在centos中安装chrome,为selenium做准备

    2024-02-08 06:56:01       53 阅读