样式没生效?使用css样式穿透

一、背景

  • 明明设置了样式,页面却没有按照预想的展示
  • 明明加了 !important,却没有任何作用,覆盖不了默认的样式;

二、问题分析

  • 你写的样式有语法问题么?
    • 答案是没有
  • 那为什么没有生效?
    • 因为你修改的不是目标元素,或者说你修改了个寂寞
    • 比如你想修改第三方ui组件的样式:
<style scope>
.EL_Dialog .el-dialog .el-dialog__header{
	background-color: cyan !important;
}
.EL_Dialog .el-dialog__footer{
	background-color: cyan !important;
}
</style>
  • 实际最后渲染的生成的是
<style>

.EL_Dialog .el-dialog .el-dialog__header[data-v-9ad4a878]{
	background-color: cyan !important;
}
.EL_Dialog  .el-dialog__footer[data-v-9ad4a878]{
	background-color: cyan !important;
}

</style>
  • 所以,您设置的不是.el-dialog__footer,而是一个元素具有属性.el-dialog__footer且有data-v-9ad4a878的属性,显然UI框架里没有这个的,这个防止样式污染加的额外的属性,可以理解为作用域。

三、问题解决: 通过样式穿透(多种方式,任君挑选)

<style>
.EL_Dialog >>> .el-dialog__body{
	background-color: cyan !important;
}


.EL_Dialog /deep/ .el-dialog__footer{
	background-color: cyan !important;
}	

.EL_Dialog ::v-deep .el-dialog__footer{
	background-color: skyblue !important;
}	


/***vue3 */
.EL_Dialog  ::v-deep(.el-dialog .el-dialog__header) {
	background-color: cyan !important;
}

/***vue3 */
.EL_Dialog  :deep(.el-dialog .el-dialog__header) {
	background-color: skyblue !important;
}
</style>
  • 最终的渲染结果
<style>
.EL_Dialog[data-v-9ad4a878] .el-dialog .el-dialog__header {
    background-color: skyblue !important;
}

.EL_Dialog[data-v-9ad4a878] .el-dialog .el-dialog__header {
    background-color: cyan !important;
}
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值