1.开发中遇到的问题
需求: 修改elementUI 中 环形 progress 宽度,由于父容器的宽度不确定,不能使用:width 属性设置宽度值,html代码如下:
<template>
<div style="width:500px;height:200px;border:1px solid red">
<div class="circlebox">
<el-progress type="circle" :percentage="25" >
</el-progress>
</div>
<div class="circlebox">
<el-progress type="circle" :percentage="80" >
</el-progress>
</div>
<div class="circlebox">
<el-progress type="circle" :percentage="67" >
</el-progress>
</div>
<div class="circlebox">
<el-progress type="circle" :percentage="36">
</el-progress>
</div>
</div>
</template>
<style lang='less' scoped>
.circleBox {
position: relative;
text-align: center;
width: 300px;
}
.circlebox{
float: left;
height: 60px;
width: calc(100%*0.25);
}
.el-progress-circle {
height: 100% !important;
width: 100% !important;
}
</style>
由于上面css 返回使用了 scoped,只能在此组件中使用,由于 el-progress-circle 是 el-progressz 自带的 class,但是却不生效,我们使用浏览器控制台看下:
从上面可以看出 el-progress-circle 这个class 属性值根本没有生效。
为什么没有生效?
因为scoped 属性是HTML5中的新属性。如果使用了该属性,那么样式仅仅应用到了 style 元素及其子元素身上。当一个style 标签拥有scoped属性时,它的CSS样式及只能作用与当前的组件,这样做的好处是: 组件之间的样式不互相污染。
如果一个项目中的style标签全部加上了scoped ,相当于组件的私有化,样式的模块化。
2.解决办法
1.去掉 scoped 属性
<style lang='less'>
.circleBox {
position: relative;
text-align: center;
width: 300px;
}
.circlebox{
float: left;
height: 60px;
width: calc(100%*0.25);
}
.el-progress-circle {
height: 100% !important;
width: 100% !important;
}
</style>
缺点: 去掉scoped 属性,样式就变成了全局样式,会污染其他组件中的 progress组件,所以不建议使用
2.样式穿透
如果vue2, 则使用
sass和less的样式穿透 使用:(/deep/)
/deep/ 修改
外层类 /deep/ 想要修改的类名 {
要修改的样式
}
<style lang="less" scoped>
.circlebox{
float: left;
height: 60px;
width: calc(100%*0.25);
/deep/ .el-progress-circle {
height: 100% !important;
width: 100% !important;
}
}
</style>
如果使用的是 vue 3.x ,不可以使用deep,会报错
通用样式穿透,使用 (::v-deep)
::v-deep .el-card__header