Merging Selectors from Mixins

Merging selectors from mixins

No. Sass has no way of merging selectors (this could be considered undesirable, as it would alter the ordering of the selectors).

The only thing you can really do is something like this (or write 2 separate mixins):

@mixin footer_flush_bottom {
height: 100%;

body {
min-height: 100%;
position: relative;
@content;
}
}

html {
// additional html styles
@include footer_flush_bottom {
// additional body styles
}
}

Combining Sass mixin selectors

If you don't mind storing your selectors in strings, you could define different field types using variables:

$input-form-fields: "input:not([type=hidden]), textarea";
$button-form-fields: "button";
$select-form-fields: "select";

Your then define your mixins with interpolated strings like so:

// Apply a set of rules to input form fields.
@mixin input-form-fields {
#{$input-form-fields} {
@content;
}
}

// Apply a set of rules to button form fields.
@mixin button-form-fields {
#{$button-form-fields} {
@content;
}
}

// Apply a set of rules to select form fields.
@mixin select-form-fields {
#{$select-form-fields} {
@content;
}
}

// Apply a set of rules to all form fields.
@mixin all-form-fields {
#{$input-form-fields},
#{$button-form-fields},
#{$select-form-fields} {
@content;
}
}

As a result, @include all-form-fields will result in

input:not([type=hidden]), textarea,
button,
select {
margin-bottom: .5em; }

Same selector across SASS Partials not being aggregated

What you're asking for would actually be incorrect behavior, because in a CSS file rule order matters. Take the following code:

.foo {
color: 'red';
}
.bar {
color: 'blue';
line-height: 1;
}
.foo {
line-height: 2;
}

You can't merge the two rules for the .foo selector, because wherever you'd put the result, it'd never keep the intended styling for elements with both foo and bar classes.

Is it possible to make functions/mixins/shorthands in Sass/SCSS that take selectors as an argument?

Yes, this is possible by using @mixin, escaping the selector inside the mixin and passing the selector into the mixin as a string.

@mixin border-different-when-hover($selector) {
#{$selector} {
border: 1px dashed currentColor;
}
#{$selector}:hover {
border: 2px solid currentColor;
}
}

@include border-different-when-hover('nav > abbr');
@include border-different-when-hover('a.kebap');
@include border-different-when-hover('#bleepable-constructor');

See https://sass-lang.com/documentation/at-rules/mixin#arguments for reference on mixins with arguments.



Related Topics



Leave a reply



Submit