Wednesday, August 2, 2023

SASS Mixins for Css Property

   
SCSS Mixin

SASS has a Mixins feature to reduce repeated code typing. CSS3 introduced some new properties like border-radius, background, box-shadow, etc., which were not available in CSS2. To support different browsers, CSS3 uses prefixes like -webkit-, -moz-, -ms-, -o- for certain properties. When using these CSS3 properties, you may end up repeating the same property values with browser prefixes, which can lead to code duplication. Mixins can help alleviate this problem.

A mixin in SASS allows you to group a set of CSS styles and reuse them wherever needed. Here's how you can use mixins:

For example, if you need a border-radius with a value of 10px, you can create a mixin like this:

scss
@mixin box-borderRadius {
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    -ms-border-radius: 10px;
    border-radius: 10px;
}

You can then call this mixin inside any CSS class where you want to apply the border-radius:

scss
.main-box-container {
    background-color: #dddddd;
    border: 1px solid #333333;
    width: 300px;
    height: 300px;
    @include box-borderRadius;
}

The output will be:

css
.main-box-container {
    background-color: #dddddd;
    border: 1px solid #333333;
    width: 300px;
    height: 300px;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    -ms-border-radius: 10px;
    border-radius: 10px;
}

Additionally, you can use variables to set default values in the mixin:

scss
@mixin border-radius($radius) {
    -webkit-border-radius: $radius;
    -moz-border-radius: $radius;
    -ms-border-radius: $radius;
    border-radius: $radius;
}

.box {
    width: 50%;
    @include border-radius(10px);
}

This will generate:

css
.box {
    width: 50%;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    -ms-border-radius: 10px;
    border-radius: 10px;
}

Furthermore, you can include a set of CSS styles within a mixin, and reuse them anywhere in the CSS file:

scss
@mixin no-bullets {
    list-style: none;
    li {
        list-style-image: none;
        list-style-type: none;
        margin-left: 0px;
    }
    ul.plain {
        color: #444;
        @include no-bullets;
    }
}

This will output:

css
ul.plain {
    color: #444;
    list-style: none;
}

ul.plain li {
    list-style-image: none;
    list-style-type: none;
    margin-left: 0px;
}

By using mixins, you can make your CSS code cleaner, more organized, and easier to maintain. It reduces redundancy and allows you to centralize and reuse styles effectively throughout your codebase.

No comments:

Post a Comment