Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with adjacent CSS Selector in Chrome and in Safari

Consider the following (Fiddle found here http://jsfiddle.net/burninromz/YDuzC/8/)

What should happen is when you click the checkbox, the appropriate label should appear. This does not work in Safari and Chrome, but on IE, Firefox and Opera. When you inspect elements in both chrome and safari, you see that the style is actually applied to the element, but is not rendered correctly. Any ideas why this is?

See below.

html

<div>
    <input type="checkbox"></input>
    <span>Unchecked</span>
    <span>Unchecked</span>

css

    input[type="checkbox"]:checked + span {
      display:none  
    }

    input[type="checkbox"] + span {
      display:block  
    }

    input[type="checkbox"]:checked + span + span {
      display:block  
    }

    input[type="checkbox"] + span + span {
      display:none  
    }

This selector does not work

input[type="checkbox"]:checked + span + span {
  display:block  
}
like image 603
CodeMonkey Avatar asked Sep 03 '13 20:09

CodeMonkey


People also ask

Why do browsers match CSS selectors from right to left?

So browsers match from the right; it gives an obvious starting point and lets you get rid of most of the candidate selectors very quickly.

How do I enable CSS selector in Chrome?

1) Install this extension to your chrome browser. 2) Inspect an element on your page or select an element on the "Elements" page of the Chrome Browser Dev tools. 3) Navigate to the "CSS Selector" tab on the sidebar of the "Elements" page of the Dev tools.

How a browser determines what elements match a CSS selector?

Browsers match selectors from rightmost (key selector) to left. Browsers filter out elements in the DOM according to the key selector and traverse up its parent elements to determine matches. The shorter the length of the selector chain, the faster the browser can determine if that element matches the selector.

Can you combine CSS selectors?

There are different methods for combining CSS selectors: Descendant (whitespace) combinator, (Level 1) Child combinator, (Level 2) Next sibling combinator, (Level 2)


1 Answers

You can try using the sibling combinator. ~ is similar to +, however, it’s less strict. While an adjacent selector will only select the first element that is immediately preceded by the former selector, this one is more generalized. It will select any elements as long as they follow the former selector in the tree.

So, your CSS would look like this...

input[type="checkbox"]:checked + span {
  display:none  
}

input[type="checkbox"] + span {
  display:block  
}

input[type="checkbox"]:checked ~ span ~ span {
  display:block  
}

input[type="checkbox"] + span + span {
  display:none  
}

Here is a working example, provided by @Adrift, using the above code: jsfiddle.net/YDuzC/10

like image 188
Kirkland Avatar answered Oct 30 '22 15:10

Kirkland