tsh
tsh

Reputation: 4738

CSS selector match certain value in style attribute

How can I write css selector for an element with specified inline styles?

For example:

<div style="top: 0; left: 0;">link1</div>
<div style="left:3px; top:0;">link2</div>
<div style="top:3px; left:0;">link3</div>

Then, I want to select link1 and link2 since they all have top:0.

I'm not sure about if I should place a space in div[style*="top: 0"] or not. How does the style attribute be setted? Will browser format the string in any format automatically?


Why I need this: I know query an element based on style attribute is not a good idea. But I'm writing user style, while I cannot modify the html page or javascript. The web page only modified the style attribute when events triggered.

Upvotes: 1

Views: 87

Answers (1)

Irvin Lim
Irvin Lim

Reputation: 2451

Since you mentioned you have no way to change the HTML, one hacky way you can do it is to account for both cases, I guess:

div[style*="top: 0"], div[style*="top:0"] {
    /* styles here */
}

An alternative would be to use JS/jQuery if you are willing.

Example for jQuery:

$('div').filter(function() {
  return parseInt($(this).css('top')) == 0;
}).addClass("yourNewClass");

Edit: Didn't notice that you mentioned you cannot alter the page via JavaScript as well, but well, leaving this in just in case.

Upvotes: 2

Related Questions