Sam Z.
Sam Z.

Reputation: 1

How can I avoid duplicated code within a nested SCSS class?

I want to avoid using duplicated code if it is possible. What I am doing right now essentially is to use similar code for #menu-icon and #close-menu were the only difference being the value of percentage I use in height: property. Is there any effective way of using SCSS to avoid using duplications of code?

@import "../../resources/Variables.scss";
header {
    position: fixed;
    background-color: $color-background;
    width: 100%;
    height: 22%;
    top: 0;
    left: 0;

    #menu-icon {
        position: absolute;
        height: 8%;
        top: 45%;
        left: 10%;
        margin-right: -50%;
        transform: translate(-50%, -50%);
        cursor: pointer;
    }

    #close-menu {
        position: absolute;
        height: 15%;
        top: 45%;
        left: 10%;
        margin-right: -50%;
        transform: translate(-50%, -50%);
        cursor: pointer;
    } 
}

Upvotes: 0

Views: 34

Answers (2)

Nachiket Patel
Nachiket Patel

Reputation: 21

You can use Mixin for avoiding duplication of code.

@mixin menu_prop($menu_height){
        height: $menu_height;
        position: absolute;
        top: 45%;
        left: 10%;
        margin-right: -50%;
        transform: translate(-50%, -50%);
        cursor: pointer;
}
header {
    position: fixed;
    background-color: $color-background;
    width: 100%;
    height: 22%;
    top: 0;
    left: 0;

    #menu-icon {
        @include menu_prop(8%);
    }

    #close-menu {
         @include menu_prop(10%);
    } 
}

Upvotes: 1

Crocsx
Crocsx

Reputation: 7609

@import "../../resources/Variables.scss";
header {
    position: fixed;
    background-color: $color-background;
    width: 100%;
    height: 22%;
    top: 0;
    left: 0;

    #menu-icon, #close-menu {
        position: absolute;
        height: 8%;
        top: 45%;
        left: 10%;
        margin-right: -50%;
        transform: translate(-50%, -50%);
        cursor: pointer;
    }

    #close-menu {
        height: 15%;
    } 
}

or just

@import "../../resources/Variables.scss";
header {
    position: fixed;
    background-color: $color-background;
    width: 100%;
    height: 22%;
    top: 0;
    left: 0;

    #menu-icon, #close-menu {
        position: absolute;
        top: 45%;
        left: 10%;
        margin-right: -50%;
        transform: translate(-50%, -50%);
        cursor: pointer;
    }
    #menu-icon{
        height: 8%;
    }

    #close-menu {
        height: 15%;
    } 
}

Upvotes: 0

Related Questions