Match only the first descendent in pure css?

后端 未结 2 880
猫巷女王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:22

    Look up CSS selectors - W3Schools CSS Selectors

    This might be what you're looking for though:
    .outer .thing:first-child {}

    You could also try nth-child()

    0 讨论(0)
  • 2021-01-29 01:34

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

    <div class="outer">
        <div class="thing">
            <div class="inner">
                <div class="thing" />
            </div>
        </div>
    </div>
    

    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:

    <div class="outer">
        <div class="thing" />
        <div class="inner">
            <div class="thing" />
        </div>
    </div>
    

    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:

    <header>
        <h1></h1>
        <p></p>
    </header>
    

    or

    <hgroup>
        <h1></h1>
        <h2></h2>
    </hgroup>
    

    or to stay away from standard tags:

    <div class="outer">
        <div class="title" />
        <div class="subtitle" />
    </div>
    

    or using multiple classes

    <div class="outer">
        <div class="title maintitle" />
        <div class="inner">
            <div class="title subtitle" />
        </div>
    </div>
    
    0 讨论(0)
提交回复
热议问题