[英]CSS/SCSS - reusable mixin for custom attribute styles
I'm styling a re-usable popout component with an arrow positioned near the box.我正在设计一个可重复使用的弹出组件,并在框附近放置一个箭头。 I'm wondering if there is a way to use a mixin to make the placement styling easier/neater?我想知道是否有一种方法可以使用 mixin 来使放置样式更容易/更整洁?
.dialog {
...
&[data-arrow-placement^='top'] {
[data-arrow] {
bottom: -12px;
}
}
&[data-arrow-placement^='bottom'] {
[data-arrow] {
top: -12px;
}
}
&[data-arrow-placement^='left'] {
[data-arrow] {
right: -12px;
}
}
&[data-arrow-placement^='bottom-right'] {
[data-arrow] {
left: -12px;
top: -12px;
}
}
}
I initially had a chain of @if being used however it seems like it would be adding more complexity than required.我最初使用了一个@if 链,但它似乎会增加比所需更多的复杂性。
How about something like this?:像这样的东西怎么样?:
@mixin arrow($placement,$position,$other:'') {
&[data-arrow-placement^='#{$placement}'] {
[data-arrow] {
#{$position}: -12px;
@if $other != '' {
#{$other}: -12px;
}
}
}
}
.dialog {
@include arrow('top','bottom');
@include arrow('bottom','top');
@include arrow('left','right');
@include arrow('bottom-right','left','top');
}
Depending on what else you want to do with this selector, I would either do like this:根据你想用这个选择器做什么,我要么这样做:
@mixin arrowPlacement($placement) {
&[data-arrow-placement^="#{$placement}"] {
[data-arrow] {
@content;
}
}
}
.dialog {
$arrowPosition: -12px;
@include arrowPlacement(top) {
bottom: $arrowPosition;
};
@include arrowPlacement(bottom) {
top: $arrowPosition;
};
@include arrowPlacement(left) {
right: $arrowPosition;
};
@include arrowPlacement(bottom-right) {
left: $arrowPosition;
top: $arrowPosition;
};
}
Or like this (you can even add a @content
if required):或者像这样(如果需要,您甚至可以添加@content
):
@mixin arrowPlacement($placement, $position, $properties...) {
&[data-arrow-placement^="#{$placement}"] {
[data-arrow] {
@each $property in $properties {
#{$property}: $position;
}
}
}
}
.dialog {
$arrowPosition: -12px;
@include arrowPlacement(top, $arrowPosition, bottom);
@include arrowPlacement(bottom, $arrowPosition, top);
@include arrowPlacement(left, $arrowPosition, right);
@include arrowPlacement(bottom-right, $arrowPosition, left, top);
}
And if you don't plan to reuse the mixin, you can use the -12px
position value directly instead of passing it as a parameter:如果你不打算重用 mixin,你可以直接使用-12px
position 值,而不是将其作为参数传递:
@mixin arrowPlacement2($placement, $properties...) {
&[data-arrow-placement^="#{$placement}"] {
[data-arrow] {
@each $property in $properties {
#{$property}: -12px;
}
}
}
}
.dialog {
@include arrowPlacement2(top, bottom);
@include arrowPlacement2(bottom, top);
@include arrowPlacement2(left, right);
@include arrowPlacement2(bottom-right, left, top);
}
The argument list (...)
will let you pass as many properties as you want. argument list (...)
将允许您传递任意数量的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.