Search code examples
csssasscompass-sass

Target the same child with two differents parent class


Since few days I'm using SASS to write my css files. I have two different parents class but this two parents have the same children classes. So I want to build my SCSS tree of this CSS code :

#header {
    position: relative;
    width: 100%;
}

#header-g {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 300;
    width: 100%;
}

#header .l-header-top, #header-g .l-header-top {
    height: 55px;
    line-height: 50px;
    border-top: 5px solid #474747;
    background-color: #f0f1f3;

    font-size: 16px;
}

I tried this but I think I forget something :

    #header {
    position: relative;
    width: 100%;

    &#header-g {
        position: fixed;
        top: 0;
        left: 0;
        z-index: 300;
        width: 100%;

        .l-header-top {
            height: 55px;
            line-height: 50px;
            border-top: 5px solid #474747;
            background-color: #f0f1f3;

            font-size: 16px;
        }
    }
}

Thanks


Solution

  • In your code, if you are using & it means that they are in the same element and in a single element there is only 1 ID. You should use a class in that situation.

    #header {
        position: relative;
        width: 100%;
    
        &#header-g {
            position: fixed;
            top: 0;
            left: 0;
            z-index: 300;
            width: 100%;
    

    but it should be something like this. #header and #header-gestion are you ID parents while they have the same children which are .l-header-top.

    #header {
        position: relative;
        width: 100%;
        .l-header-top {
           height: 55px;
           line-height: 50px;
           border-top: 5px solid #474747;
           background-color: #f0f1f3;
    
           font-size: 16px;
        }
    }
    
    #header-g {
        position: fixed;
        top: 0;
        left: 0;
        z-index: 300;
        width: 100%;
        .l-header-top {
           height: 55px;
           line-height: 50px;
           border-top: 5px solid #474747;
           background-color: #f0f1f3;
    
           font-size: 16px;
        }
    }
    

    Or you use & in this way which is based on BEM Methodology in class naming conventions. You can check this link: BEM — Block Element Modifier Methodology

    #header {
        position: relative;
        width: 100%;
        &-g {
           position: fixed;
           top: 0;
           left: 0;
           z-index: 300;
           width: 100%;
        }
    }
    
    
    #header,
    #header-g {
        .l-header-top {
           height: 55px;
           line-height: 50px;
           border-top: 5px solid #474747;
           background-color: #f0f1f3;
           font-size: 16px;
        }
    }