简体   繁体   中英

CSS3 :not() selector, working around contained elements

I am moving clarification to the top of this post: When the mouse is not hovering over a certain div, I want elements other than this div to have a red background-color. Can this be achieved with a not() selector as seen in this post? The predicament appears to be that since the certain div is within a body element, the mouse will always be hovering over the body element even when it's over the certain div, thus the body will always have a red background-color.

I am trying to use the not() selector to affect elements when hovering over elements that are not within my selection.

For example:

  [data-panel] { background-color:white; } :not([data-panel=visible]):hover { background-color:red; } 
 <body> <div data-panel='visible'> <div data-panel='visible'>Content</div> </div> </body> 

My desired outcome is that if the mouse is hovering anywhere besides those div s, the background-color will change to red (ie hovering in the body).

However, since those div s are within the body, that selector will always be active. The body will always be red. Is there anyway to style those div s so that this doesn't happen? Maybe something with z-index ? Any clues?

Don't quote your attribute selector.

As already mentioned by James ; panel is not a valid HTML5 attribute. You should be taking advantage of HTML5's data-* attributes.

 :not([data-panel=visible]):hover { background-color:red; } 
 <div data-panel='visible'> <div data-panel='visible'>Content</div> </div> 

This of course, affects all elements that don't have the matching attribute, including <body> , which is while your entire page's background will turn red when hovered.

Edit

The predicament appears to be that since the certain div is within a body element, the mouse will always be hovering over the body element even when it's over the certain div, thus the body will always have a red background-color

There is no CSS parent selector, so an event on an element within the body, can't have any say over any styles applied to the body.

What you are trying to do is not possible with CSS alone.

To achieve that effect – let the body turn red on :hover, but not when hovering the panels – you have to cancel the pointer event bubbling on the panels. This is only possible using JS.

BTW, HTML5 has a method to define own attributes: the data-* attributes ; eg data-panel="visible" .

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