Search code examples
csscss-selectorspseudo-element

nth-child and before


I'm having an CSS problem, i need to achieve this

article div#comments-wrapper ul.sub-comment:before {
    width:1px;
    height:67px;
    background-color:#e4e4e4;
    position:absolute;
    margin-left:-595px;
    margin-top:-36px;
    content:'';
}
article div#comments-wrapper ul.sub-comment:nth-child(1):before {
    height:37px;
    margin-top:-6px;
}

but i can't put two pseudo elements like that, and i've tested it (doesn't work), also tried some other ways but didn't manage to figure it out.


Solution

  • :nth-child() doesn't filter by classes or anything. In your code, your first ul.sub-comment isn't the very first child in #comments-wrapper, so it doesn't work.

    Instead, use this selector technique and invert your height and margin-top styles as follows:

    article div#comments-wrapper ul.sub-comment:before {
        width:1px;
        height:37px; /* was 67px in your code */
        background-color:#e4e4e4;
        position:absolute;
        margin-left:-595px;
        margin-top:-6px; /* was -36px in your code */
        content:'';
    }
    article div#comments-wrapper ul.sub-comment ~ ul.sub-comment:before {
        height:67px; /* was 37px in your code */
        margin-top:-36px; /* was -6px in your code */
    }
    

    Basically, instead of :nth-child(1) (or :first-child for that matter), use a sibling selector with another ul.sub-comment to apply the original styles to all subsequent ul.sub-comment elements after the first one.

    Updated fiddle (also inverted the background-color styles so the first one remains blue)