如何将多个选择器与相邻的兄弟选择器组合?

时间:2016-01-28 04:43:38

标签: css css-selectors

所以我有以下的样式组合,我想要的。如果按钮处于innerHTMLfocus状态,则按钮的active

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; } active状态时,该样式将起作用。但是我尝试的每个组合都失败了,例如:

focus

我也尝试过:

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

都没有奏效。我可以坚持使用不同的样式,但我很好奇有没有办法将它们正确组合并考虑 .new-comment-input:focus:active + .new-comment-button, .new-comment-button:focus { visibility: visible; } 的两种状态?

2 个答案:

答案 0 :(得分:1)

你唯一能做的就是删除无关的{ visibility: visible; }并用逗号替换它:

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

您有四个选择器分为两个规则集,但您无法将它们中的任何一个组合在一起,因此您只需将它们的两个组合并为一个。 :focus:active同时表示这两个状态(AND),而不是其中任何一个(OR),因此您无法以这种方式组合它们。

答案 1 :(得分:0)

如果你的目标浏览器支持它,你可以使用any

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

目前,您需要将供应商前缀设为-webkit-any等。最终,这将标准化为:matches。请参阅https://developer.mozilla.org/en-US/docs/Web/CSS/:any