Match only the first descendent in pure css?

后端 未结 2 928
猫巷女王i
猫巷女王i 2021-01-29 01:04

Is there an elegant way in pure css to match only the first descendent -- similar to jquery first()?

in jQuery:

$(\".outer .title\").first();
         


        
2条回答
  •  忘掉有多难
    2021-01-29 01:34

    Update: this answer is based on a structure which has now been edited in the question:

    With nesting like that, the best option is to revert the styles if the object is within itself;

    .outer .thing { /* styles */ }
    .thing .thing { /* revert styles */ }
    

    With a structure like this:

    You have fewer options;

    /* assume thing will always be a direct child of outer */
    .outer > .thing {}
    
    /* assume thing will always be the VERY FIRST child of outer */
    .outer > thing:first-child {}
    
    /* assume thing will always be inside the VERY FIRST child of outer */
    .outer > .thing:first-child, .outer > *:first-child .thing {}
    
    /* assume the thing you don't want will always be inside inner */
    .outer .thing {}
    .inner .thing { /* revert styles */ }
    

    Both structures are silly though. This looks like headings/sub-headings, in which case you can do this:

    or

    or to stay away from standard tags:

    or using multiple classes

提交回复
热议问题