Reputation: 690
I want to create a sass file that the selectors will be attribute selectors.
When I work with class selectors, in most of the cases I will do
.parent {
&-child {
}
}
which gives me the following css: .parent-child {}
.
I want to achieve the same thing with attribute selectors:
[data-parent] {
&-child {
}
}
which I want to become: [data-parent-child] {}
someone knows how to achieve this? thanks.
Upvotes: 5
Views: 5732
Reputation: 2418
You can use this mixin
as a workaround to get the desired result.
@mixin child-attribute($child) {
$string: inspect(&);
$original: str-slice($string, 3, -4);
@at-root #{ selector-replace(&, &, "[#{$original}#{$child}]" ) } {
@content;
}
}
The code simply does the following
inspect
function$string
variable i.e the value 'data-parent'
from '([data-parent])'
$original
variable and child
variableWhen used in the following ways
[data-parent] {
@include child-attribute('-child') {
color: green;
}
}
The css output
[data-parent-child] {
color: green;
}
Depending on what you want to achieve, it can also be used like this
[grandparent] {
@include child-attribute('-parent') {
color: white;
@include child-attribute('-child') {
color: blue;
}
}
}
Which generates the following css
[grandparent-parent] {
color: white;
}
[grandparent-parent-child] {
color: blue;
}
Hope this helps you
Upvotes: 3
Reputation: 455
I would go down a slightly different route of having a class
on your elements that contain the data
attributes.
<div class="data-obj" data-parent="true"></div>
<div class="data-obj" data-parent-child="true"></div>
then in your SASS do
.data-obj {
...
&[data-parent] { ... }
&[data-parent-child] { ... }
}
Upvotes: -1
Reputation: 5350
You can create mixin
that will set styles for elements with data attribytes.
Scss:
@mixin data($name) {
[data-#{$name}] {
@content;
}
}
* {
@include data('lol') {
color: red;
};
}
Css output:
* [data-lol] {
color: red;
}
Upvotes: -1