说我有一些像css这样的css:
.modal-350 {
width: 350px;
}
.modal-400 {
width: 400px;
}
.modal-500 {
width: 500px;
}
等。仅使用CSS是否可以仅从类名设置宽度(或其他属性)?
我知道在javascript中这很简单,我也可以使用:
.modal-auto {
display: inline-block;
width:auto;
}
这不是生产代码,我只是好奇。
答案 0 :(得分:1)
没有。即使我们can use variables in CSS,我们只能在属性值中执行此操作,而不能在选择器名称中执行此操作。所以这样的事情不工作:
.modal-$size {
width: ${size}px;
}
但是,您可以使用CSS预处理器,例如LESS或SASS,并根据请求的大小自动生成此类规则。
SASS示例:
$modal-sizes: 50 100 200 500;
%modal-default {
border-radius: 50%;
color: red;
background: green;
border-color: blue;
}
@mixin modals {
@each $size in $modal-sizes {
.modal-#{$size} {
@extend %modal-default;
width: #{$size}px;
}
}
}
@include modals;
这将编译为:
.modal-50, .modal-100, .modal-200, .modal-500 {
border-radius: 50%;
color: red;
background: green;
border-color: blue;
}
.modal-50 {
width: 50px;
}
.modal-100 {
width: 100px;
}
.modal-200 {
width: 200px;
}
.modal-500 {
width: 500px;
}