Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS attribute selector + descendant gives a bug in Webkit?

Consider this CSS:

[data-color="red"] h1 {
background-color:red;
}

[data-color="blue"] h1 {
background-color:blue;
}

And this HTML:

<div data-color="red">
<h1>red</h1>
</div>

<div data-color="blue">
<h1>blue</h1>
</div>

<div data-color="blue">
<h1>blue</h1>
</div>

Now take a look at the following demo of the above code in Webkit and any other browser:
http://jsfiddle.net/aUCkn/

What's strange is that if you put each h1 on the same line, i.e.:

<div data-color="red"><h1>red</h1>
</div>

<div data-color="blue"><h1>blue</h1>
</div>

<div data-color="blue"><h1>blue</h1>
</div>

It works in Webkit too:
http://jsfiddle.net/aUCkn/1/

Does anyone know where this comes from? Am I doing something wrong or is Webkit acting stupid here?

like image 237
DADU Avatar asked Jul 11 '11 19:07

DADU


People also ask

What is CSS descendant selector?

The descendant selector is a way to select elements that are located somewhere underneath other elements, according to the tree structure of the webpage. This selector is actually multiple selectors combined together, but separated by a space.

Which selector is used to select the paragraph element that is a direct descendant of section?

A parent-child selector matches when an element is the direct descendent of some parent element. A parent-child selector is made up of two or more selectors separated by a tilde (~). A parent-child selector may also contain attribute selectors.

What is descendant in HTML?

A descendant refers to any element that is connected but lower down the document tree - no matter how many levels lower. In the diagram below, all elements that are connected below the <div> element are descendants of that <div>.


2 Answers

The first jsFiddle is broken in my Chrome 12.0.742.112 (stable).

However, it works in my Chrome 14.0.803.0 dev-m.

So, they're already aware of and have fixed the bug. You just have to wait for the fix to land in the stable channel.

I'll try to find a link to a bug report, if one exists.

like image 82
thirtydot Avatar answered Oct 14 '22 12:10

thirtydot


Try adding [_] {} to your CSS (doesn't matter where).

In reality, it can be any attribute selector rule, without a descendant clause, that will potentially match the attributed elements selected by the original selectors, i.e.: [data-color] {} and div[data-color] {} will fix the others, but a[data-color] {} will not fix it.

I've tested it on the posted fiddle (http://jsfiddle.net/aUCkn/) and it works for Safari (5.1.2).

My co-worker and I found it after playing with lots of random ideas for workarounds.

like image 3
Michael Morton Avatar answered Oct 14 '22 12:10

Michael Morton