在LESS中使用&-...语法时,如何继承父选择器的position属性?
问题分析与解决方案
你的SCSS代码编译后,.point-blue是独立选择器,和.point没有样式继承关系,所以不会自动获得position: absolute。原因是&-blue中的&指代父选择器.point,最终会被编译成.point-blue,和.point是平级的两个选择器,自然不会共享样式。
下面是几种满足你需求的解决方案:
方案1:用@extend继承基础样式
这是最直接的方法,让.point-blue继承.point的所有样式,仅覆盖颜色:
.map-container { position: relative; .map { width: 100%; height: 100%; } .point { position: absolute; color: red; } .point-blue { @extend .point; color: blue; } }
编译后的CSS会合并基础样式:
.map-container .point, .map-container .point-blue { position: absolute; color: red; } .map-container .point-blue { color: blue; }
这样.point-blue自动拥有绝对定位,同时颜色被覆盖为蓝色。
方案2:用混合宏(Mixin)复用公共样式
如果后续需要更多颜色变体,用Mixin管理公共样式更灵活:
// 定义公共样式的Mixin @mixin point-base { position: absolute; } .map-container { position: relative; .map { width: 100%; height: 100%; } .point { @include point-base; color: red; } .point-blue { @include point-base; color: blue; } }
编译后每个标记点类都会包含position: absolute,避免重复编写定位代码。
内容的提问来源于stack exchange,提问作者Ptolemy2002
相关产品推荐
相关产品推荐

