You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用CSS实现奇偶<article>内图片交替左右浮动?

用CSS实现奇偶article内图片交替浮动的方案

你可以直接通过CSS的:nth-child或:nth-of-type选择器,选中奇偶位置的<article>元素,再嵌套.service_pic类设置浮动样式,完全不用手动给元素加类,后续新增article时会自动套用样式,减少维护成本。

核心CSS代码

如果<article>的父容器里只有article元素,用:nth-child即可:

/* 奇数位article内的图片右浮动 */
article:nth-child(odd) .service_pic {
  float: right;
  margin-left: 1rem; /* 避免文字紧贴图片,可按需调整 */
}

/* 偶数位article内的图片左浮动 */
article:nth-child(even) .service_pic {
  float: left;
  margin-right: 1rem;
}

如果父容器中还包含其他类型元素(比如标题、非article的div等),推荐用:nth-of-type,它只会统计同类型的<article>元素,避免位置判断错误:

article:nth-of-type(odd) .service_pic {
  float: right;
  margin-left: 1rem;
}

article:nth-of-type(even) .service_pic {
  float: left;
  margin-right: 1rem;
}

额外优化:解决浮动高度塌陷问题

浮动元素会导致父元素<article>高度塌陷,给article加以下样式即可修复:

article {
  overflow: auto;
  margin-bottom: 1.5rem; /* 可选:增加article之间的间距,提升美观度 */
}

内容的提问来源于stack exchange,提问作者Taylor Satula

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 08:20:27