Sass @mixin और @include

Sass Mixin

@mixin 指令可让您创建可在整个网站中重复使用的 CSS 代码。

创建 @include 指令是为了让您使用(引用)mixin。

定义 Mixin

mixin 是用 @mixin 指令定义的。

Sass @mixin 语法:

@mixin name {
  property: value;
  property: value;
  ...
}

इस उदाहरण में "important-text" नाम का mixin बनाया गया है:

SCSS व्याकरण:

@mixin important-text {
  color: red;
  font-size: 25px;
  font-weight: bold;
  border: 1px solid blue;
}

सूचना:

Sass में खड़े और निशान के बारे में सूचना: खड़े और निशान को एक से माना जाता है。

इसका मतलब है @mixin important-text { } और @mixin important_text { } एक ही mixin के रूप में माना जाता है!

Mixin का उपयोग करना

@include इस निर्देश का उपयोग mixin को उद्धृत करने के लिए किया जाता है。

Sass @include mixin व्याकरण:

selector {
  @include mixin-name;
}

इसलिए, यदि आप उपरोक्त important-text mixin को शामिल करना चाहते हैं:

SCSS व्याकरण:

.danger {
  @include important-text;
  background-color: green;
}

Sass ट्रांसलेटर उपरोक्त कोड को सामान्य CSS में बदल देगा:

CSS आउटपुट:

.danger {
  color: red;
  font-size: 25px;
  font-weight: bold;
  border: 1px solid blue;
  background-color: green;
}

Mixin दूसरे mixin को भी शामिल कर सकता है:

SCSS व्याकरण:

@mixin special-text {
  @include important-text;
  @include link;
  @include special-border;
}

वेरियेबल को Mixin को पास करना

Mixins पैरामीटर को ग्रहण करते हैं। इस तरह, आप mixin में वेरियेबल पास कर सकते हैं。

दो पैरामीटर वाले mixin को परिभाषित करने के लिए इस तरह काम करें:

SCSS व्याकरण:

/* दो पैरामीटर वाले mixin को परिभाषित करना */
@mixin bordered($color, $width) {
  border: $width solid $color;
}
.myArticle {
  @include bordered(blue, 1px);  // दो मान वाले mixin को आह्वान करना
}
.myNotes {
  @include bordered(red, 2px); // दो मान वाले mixin को आह्वान करना
}

ध्यान दें कि पैरामीटर वेरियेबल के रूप में सेट किए गए हैं और फिर बॉर्डर प्रॉपर्टी (रंग और चौड़ाई) के मान के रूप में इस्तेमाल किए जाते हैं。

कम्पाइल के बाद, CSS इस तरह होगा:

CSS आउटपुट:

.myArticle {
  border: 1px solid blue;
}
.myNotes {
  border: 2px solid red;
}

Mixin के डिफ़ॉल्ट मान

भी mixin वेरियेबल के लिए डिफ़ॉल्ट मान निर्धारित कर सकते हैं:

SCSS व्याकरण:

@mixin bordered($color: blue, $width: 1px) {
  border: $width solid $color;
}

तब, आपको केवल mixin को रेफ़र करते समय बदलने वाले मान निर्दिष्ट करना होगा:

SCSS व्याकरण:

.myTips {
  @include bordered($color: orange);
}

Mixin के रूप में सप्लायर प्रीफ़िक्स का उपयोग करना

Mixin का एक अन्य अच्छा उपयोग (ब्राउज़र) सप्लायर प्रीफ़िक्स है।

यह एक ट्रांसफॉर्म का उदाहरण है:

SCSS व्याकरण:

@mixin transform($property) {
  -webkit-transform: $property;
  -ms-transform: $property;
  transform: $property;
}
.myBox {
  @include transform(rotate(20deg));
}

कम्पाइल के बाद, CSS इस तरह दिखेगा:

CSS व्याकरण:

.myBox {
  -webkit-transform: rotate(20deg);
  -ms-transform: rotate(20deg);
  transform: rotate(20deg);
}