Selector for one tag directly followed by another tag

后端 未结 4 1124
死守一世寂寞
死守一世寂寞 2020-12-30 18:18

This selects all tags directly preceded by tags:

A+B {
    /* styling */
}

What is t

相关标签:
4条回答
  • 2020-12-30 18:37

    Although it's not very handy, nowadays you could achieve this behavior by reversing the order of your elements both when you generate the HTML and by applying the CSS rules: display: flex and flex-direction: column-reverse

    ul {
      display: flex;
      flex-direction: column-reverse;
    }
    
    .b ~ .a {
      color: red;
    }
    <ul>
        <li class="a">A 3</li>
        <li class="c">C 2</li>
        <li class="c">C 1</li>
        <li class="b">B 1</li>
        <li class="a">A 2</li>
        <li class="a">A 1</li>
    </ul>

    Also, if you have 2 or more inline elements, you could achieve it by applying float: right, as they will be displayed in reverse order:

    ul {
      float: left;
      list-style-type: none;
    }
    
    li {
      float: right;
    }
    
    li:not(:first-child) {
      margin-right: 20px;
    }
    
    .b ~ .a {
      color: red;
    }
    <ul>
        <li class="a">A 3</li>
        <li class="c">C 2</li>
        <li class="c">C 1</li>
        <li class="b">B 1</li>
        <li class="a">A 2</li>
        <li class="a">A 1</li>
    </ul>

    0 讨论(0)
  • 2020-12-30 18:38

    You can ONLY do the converse: This selects all tags directly preceded by tags.

    This is logically equivalent to your request.

    I often use this to style a row of many checkboxes with labels

    CSS:

    label+input {
        margin-left: 4px;
    }
    

    DOM:

    <input id="a" name="a" type="checkbox"/><label for="a">...</label>
    <input id="b" name="b" type="checkbox"/><label for="b">...</label>
    <input id="c" name="c" type="checkbox"/><label for="c">...</label>
    
    0 讨论(0)
  • 2020-12-30 18:40

    You can’t in css.

    Edit: To be a bit more helpful, if you use for example jQuery (a JavaScript library), you can use .prev().

    0 讨论(0)
  • 2020-12-30 19:00

    Do you mean to style A given that it has a B element directly inside or followed? Like this:

    <A>
        <B>
        </B>
    </A>
    
    // OR
    
    <A>
    </A>
    <B>
    </B>
    

    You can't do such a thing in CSS (yet). Eric Meyer states that this kind of selector has been discussed quite a few times on the CSS mailing list, and isn’t doable. Dave Hyatt, one of the core WebKit developers, comments with a good explanation of why it can’t be done.

    Check out: Shaun Inman's blog post and the comment by Eric Meyer.
    David Hyatt weighs in, too.

    0 讨论(0)
提交回复
热议问题