QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

查看: 722|回复: 0

[HTML/CSS/JS] 实现自适应九宫格布局

[复制链接]

等级头衔

积分成就    金币 : 2861
   泡泡 : 1516
   精华 : 6
   在线时间 : 1321 小时
   最后登录 : 2025-7-2

丰功伟绩

优秀达人突出贡献荣誉管理论坛元老活跃会员

联系方式
发表于 2023-12-20 09:46:50 | 显示全部楼层 |阅读模式
如果你有一个列表,希望在页面上一行展示三个元素,可以使用 CSS 中的弹性布局(flexbox)来实现。% r) b+ O' c1 `. E- L  ]
1.jpg 0 Z4 j, K2 x2 h  W  |& }
HTML 结构:
& @% Z, O0 m9 h! F
<div class="container">
  <div class="list-item">Item 1</div>
  <div class="list-item">Item 2</div>
  <div class="list-item">Item 3</div>
  <div class="list-item">Item 4</div>
  <div class="list-item">Item 5</div>
  <!-- 其他列表项 -->
</div>
CSS 样式:
# M+ _0 [5 L- _  l
.container {
  display: flex;
  flex-wrap: wrap;
}

.list-item {
  flex: 0 0 33.33%;
  /* 或者使用 flex-basis 属性
     flex-basis: 33.33%;
  */
  /* 其他样式属性,例如边距、填充等 */
}
在上面的示例中,我们创建了一个包含列表项的容器 <div class="container">,并为每个列表项添加了类名 <div class="list-item">。通过设置容器的显示属性为 flex,并使用 flex-wrap: wrap 来使得列表项可以换行。通过设置列表项的 flex 属性为 0 0 33.33%,或者使用 flex-basis: 33.33%,我们将宽度平均分配给每个列表项,使其一行显示三个。
' v4 t7 q' G1 `! ?' O% h5 W) ?你可以根据实际情况调整容器和列表项的样式,例如添加边距、填充等。如果列表项的数量超过三个,超出的列表项会自动换行到下一行。1 o& j! K( e; n* T  f5 X9 }  e" O
如果只有中间的一个元素需要左右间隙,而页面的左边和右边不需要间隙,你可以使用 CSS 的 margin 属性来实现。下面是相应的代码示例:
9 B# n+ d9 B8 M- kHTML 结构:
<div class="container">
  <div class="list-item">Item 1</div>
  <div class="list-item with-margin">Item 2</div>
  <div class="list-item">Item 3</div>
  <div class="list-item">Item 4</div>
  <div class="list-item with-margin">Item 5</div>
  <!-- 其他列表项 -->
</div>
CSS 样式:
, ~) _$ }* d$ c+ B
.container {
  display: flex;
  flex-wrap: wrap;
}

.list-item {
  flex: 0 0 calc(33.33% - 10px); /* 考虑到间隙,减去 10px */
  margin-top: 5px; /* 上方间隙为 5px */
  margin-bottom: 5px; /* 下方间隙为 5px */
  /* 其他样式属性,例如背景颜色、文字样式等 */
}

.with-margin {
  margin-left: 15px; /* 左边间隙为 15px */
  margin-right: 15px; /* 右边间隙为1 5px */
}
在上面的示例中,我们为中间的元素添加了一个额外的类名 .with-margin,并使用该类名来设置左右间隙。
6 z$ g3 b4 J) I% q- B/ V我们使用 calc() 函数来计算每个列表项的宽度,考虑到间隙,我们将宽度设置为 33.33% - 10px。每个元素减去 10px 那么一行的就预留出了 30px 的间隙。对于具有 .with-margin 类名的元素,我们使用 margin-left 和 margin-right 属性为其添加左右各 15px 的间隙。
4 L. C5 E$ m8 i' [这样,只有中间的一个元素会有左右间隙,而页面的左边和右边则没有间隙。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|paopaomj.COM ( 渝ICP备18007172号|渝公网安备50010502503914号 )

GMT+8, 2025-7-4 10:02

Powered by paopaomj X3.5 © 2016-2025 sitemap

快速回复 返回顶部 返回列表