简体   繁体   中英

CSS Sibling selector doesn't work inside :not()

I know that with pure CSS it's impossible to select previous siblings of the element. But I try to fool browser with a complex selector.
Please see this jsFiddle . It contains several CSS rules that work fine except 2 of them:

//set border color to white for all elements before .selected and .selected itself
div:not(.selected ~ div) {
    border-color: #fff;
}

//set border color to green for the element previous to .selected
div:not(.selected ~ div):nth-last-child(2) {
    border-color: #0f0;
}

But seems that inside :not() sibling selector ~ doesn't work.
So there're 2 questions:

  1. Is it expected that ~ doesn't work inside :not() ?
  2. Is there any work-around for such case?

EDIT:
The final idea is to make a nice hover effect with pure CSS like:在此处输入图像描述
The hovered image is simply scaled, image to right of it could be found and styled easily but the left one... The example with divs is just an example.

:not() pseudo-class could not contain sibling selector.

http://dev.w3.org/csswg/selectors3/#negation

The negation pseudo-class, :not(X), is a functional notation taking a simple selector (excluding the negation pseudo-class itself) as an argument.

http://dev.w3.org/csswg/selectors3/#simple-selectors-dfn

A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, or pseudo-class.

If you want to:

set border color to white for all elements before .selected and .selected itself

I would suggest to default the border color to white and change it after .selected :

 div { display: inline-block; border: 1px solid #fff; width: 30px; } div.selected ~ div { border-color: #000; }
 <div>A</div> <div>B</div> <div class="selected">C</div> <div>D</div> <div>E</div> <div>F</div> <div>G</div>

For the second rule:

set border color to green for the element previous to .selected

If you know wich one will be selected in advance, you can target the element before with nth-child() otherwise you will need some JS to select it.

An other approach if the .selected class is dynamicaly added would be to use the same mechanism (PHP, JS or other) to give a class to the privious element at the same time and apply CSS to that class.

It is possible since CSS Level 4.

https://www.w3.org/TR/selectors-4/

The negation pseudo-class, :not(), is a functional pseudo-class taking a selector list as an argument.

Also it is changed from :not( <selector># ) to :not( <complex-selector-list> ) in https://developer.mozilla.org/en-US/docs/Web/CSS/:not#syntax in November 2018 .

See browser compatibility for "Selector list argument" in https://developer.mozilla.org/en-US/docs/Web/CSS/:not#browser_compatibility .

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