CSS selector for element within element with inline style?
Asked Answered
S

4

31

Is there a CSS selector to target elements with inline styles? So can I target the first span but not the 2nd with CSS only?

If not, can this be done with jQuery?

http://jsfiddle.net/TYCNE/

<p style="text-align: center;">
    <span>target</span>
</p>

<p>
    <span>not target</span>
</p>
​
Solar answered 3/1, 2013 at 13:16 Comment(1)
It depends. Are you only interested in the presence of the inline style attribute, or do you need to select by a specific inline style? Selecting by just merely having the attribute is easy and reliable, but having a specific inline style... not so much, unless you can control the markup.Loaded
U
27
p[style="text-align: center;"] {
  color: red;
}

However this is ugly.

Unsaddle answered 3/1, 2013 at 13:19 Comment(4)
And fails, unless the style string is an exact match.Richia
Plus one for David's comment. If the paragraph has any other styling associated with it then you have to include that in the CSS declaration.Dhole
I've had a case where IE ignored such a rule.Darendaresay
Check developer's tool in IE, sometimes IE convert styles such as hex color values into RGB values. You need to match those changes as well.Turves
P
61

A bit late to the tea party but thought I would share the solution I found & use.

@simone's answer is perfect if you can match the style attribute exactly. However, if you need to target an inline style attribute that may have other inline styles associated with it you can use:

p[style*="text-align:center;"]

"*=" means "match the following value anywhere in the attribute value."

For further reference or more detailed information on other selectors see this blog post on css-tricks.com:

The Skinny On CSS Selectors

http://css-tricks.com/attribute-selectors/#rel-anywhere

Peper answered 29/3, 2013 at 6:34 Comment(0)
U
27
p[style="text-align: center;"] {
  color: red;
}

However this is ugly.

Unsaddle answered 3/1, 2013 at 13:19 Comment(4)
And fails, unless the style string is an exact match.Richia
Plus one for David's comment. If the paragraph has any other styling associated with it then you have to include that in the CSS declaration.Dhole
I've had a case where IE ignored such a rule.Darendaresay
Check developer's tool in IE, sometimes IE convert styles such as hex color values into RGB values. You need to match those changes as well.Turves
A
10

If you would like to apply styles to a particular rule declaration you can also use style*. This will match all elements that have the inline style, regardless of the value applied.

div[style*="background-image"] {
  background-size: cover;
  background-repeat: no-repeat;
}
Aport answered 25/8, 2015 at 1:15 Comment(0)
I
2

use :

​p[style] span {
  color: red;   
}​
Irrepealable answered 3/1, 2013 at 13:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.