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

SCSS如何移除后接img标签的p元素的margin-bottom样式

解决方案

方案1:使用:has()伪类(推荐,兼容性覆盖95%+用户)

这个方案逻辑最直观,直接匹配「下一个相邻兄弟为img的p标签」,直接取消其底部边距:

.wysiwyg {
  p {
    margin-bottom: 20px;
    // 匹配下一个相邻节点是img的p元素
    &:has(+ img) {
      margin-bottom: 0;
    }
  }
  // 可自行设置img的上下间距
  img {
    margin-block: 16px; // 对应上下边距,也可以写margin: 16px 0
  }
}

支持版本:Chrome 105+、Firefox 121+、Safari 15.4+,如果你的项目不需要兼容2023年之前的浏览器版本,优先选这个方案。

方案2:兼容旧浏览器的替代方案

如果需要兼容不支持:has()的旧浏览器,可以用相邻兄弟选择器反向处理,抵消p标签的底部边距:

.wysiwyg {
  p {
    margin-bottom: 20px;
  }
  img {
    margin-block: 16px;
    // 如果img紧跟在p标签后面,将顶部margin减去p的底部边距20px
    p + & {
      margin-top: calc(16px - 20px); // 这里的16px是你想要的p和img之间的最终间距,可自行调整
    }
  }
}

这个方案兼容所有主流浏览器,包括IE11。


内容的提问来源于stack exchange,提问作者Donnie Berry

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:36:03