css穿透(带案例详解)

问题背景
在使用vue构建项目的时候,引用了第三方组件库,只需要在当前页面修改第三方组件库的样式,以做到不污染全局样式。通过在样式标签上使用scoped,达到样式只作用到本页面的目的,但是此时再修改组件样式就不起作用了。

<div class="text-box" v-html="emotion(item.content)"></div>
<style lang="stylus" scoped>
.text-box{
      color: #2e3135;
      font-size: 14px
      line-height 20px
      max-height 50px
      display: -webkit-box;
      -webkit-box-orient: vertical;
      text-overflow: ellipsis;
      overflow: hidden;
      -webkit-line-clamp: 2
 }
</style>

vue中的scoped属性的效果主要通过PostCSS转译实现

<div data-v-3ef06b24="" class="text-box">
    <h3 style="color:#1E90FF" ;="">
        <strong>【数说·有奖互动】第8期 #技术干货# 运维经验分享</strong>
     </h3> 
     【参与规则】:在#技术干货#话题下发数说,分享您的运维工作经验/有趣故事。 
     (比如给大家分享一个故障处理经过。如篇幅较长,建议发文章然后插入链接到数说)
     【活动奖励】:我们将根据内容质量和互动热度选3位网友送《程序员面试笔试宝典》
     或以下任选图书1本,同时也会抽 5 位幸运鹅,送50墨值奖励~ 
     【活动时间】:8月12日——8月19日10:00
</div>
<style lang="stylus" scoped>
.text-box[data-v-3ef06b24] {
    color: #2e3135;
    font-size: 14px;
    line-height: 20px;
    max-height: 50px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    text-overflow: ellipsis;
    overflow: hidden;
    -webkit-line-clamp: 2;
}
</style>

简单原理
通过 >>> 穿透scoped,iview中需要在组件上使用i-class声明第三方组件类名

<style scoped>
    外层 >>> 第三方组件类名{
        样式
    }
</style>

穿透方法实际上违反了scoped属性的意义。而且在vue中过多使用scoped,导致页面打包文件体积增大。
通常能写在index中的样式尽量写在index中,我们可以通过在index样式中通过外层组件添加唯一class来区分组件+第三方样式来实现类似于scoped的效果,又方便修改各种第三方组件的样式。

应用

<div class="text-box" v-html="emotion(item.content)"></div>
<style lang="stylus" scoped>
.text-box{
      color: #2e3135;
      font-size: 14px
      line-height 20px
      max-height 50px
      display: -webkit-box;
      -webkit-box-orient: vertical;
      text-overflow: ellipsis;
      overflow: hidden;
      -webkit-line-clamp: 2;
      & >>> strong {
        font-size: 14px
        overflow: hidden;
        line-height 20px
      }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值