简体   繁体   中英

How to combine multiple selectors with Adjacent sibling selector?

So I have the following combination of styles that does work as I want. If a button is either in focus or active state then the button's visibility: visible;

  .new-comment-button {
    margin: 0.25em 0 0.5em 0;
    float: right;
    visibility: hidden;
  }

  .new-comment-input:focus + .new-comment-button, 
  .new-comment-button:focus {
    visibility: visible;
  }

 .new-comment-input:active + .new-comment-button,
  .new-comment-button:active {
    visibility: visible;
  }

What I wanted to do is combine the last 2 styles into a single one that would work when the input was in a state of either active or focus . However every combination I tried failed like the following for example:

  .new-comment-input:focus + .new-comment-button,
  .new-comment-input:active + .new-comment-button, 
  .new-comment-button:focus {
    visibility: visible;
  }

I also tried:

  .new-comment-input:focus:active + .new-comment-button,
  .new-comment-button:focus {
    visibility: visible;
  }

Neither worked. I can stick with the separate styles, but I was curious is there was a way to properly combine them and account for both states of the input ?

The only thing you can do is to remove the extraneous { visibility: visible; } { visibility: visible; } and replace it with a comma:

.new-comment-input:focus + .new-comment-button, 
.new-comment-button:focus,
.new-comment-input:active + .new-comment-button,
.new-comment-button:active {
  visibility: visible;
}

You have four selectors split into two rulesets, but you can't combine any of them so you have to simply merge their two groups into one. :focus:active means both of those states at the same time (AND), not either one of them (OR), so you can't combine them that way.

You could use any for this, if your targeted browsers support it:

.new-comment-input:any(:focus, :active) + .new-comment-button,
.new-comment-button:any(:focus, :active) {
  visibility: visible; 
}

At the moment, you will need to vendor prefix as -webkit-any etc. Eventually, this will be standardized as :matches . See https://developer.mozilla.org/en-US/docs/Web/CSS/:any .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM