106

If I set a CSS value on a specific element using:

$('#element').css('background-color', '#ccc');

I want to be able to unset that element-specific value and use the cascaded value, along the lines of:

$('#element').css('background-color', null);

But that syntax doesn't seem to work – is this possible using another syntax?

Edit: The value isn't inherited from the parent element – the original values comes from an element-level selector. Sorry for any confusion!

0

6 Answers 6

162

From the jQuery docs:

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style> element.

Sign up to request clarification or add additional context in comments.

1 Comment

I came across this question when I had this problem. In my case I was setting the css attribute in a style attribute on the tag, so this method did not work. Applying the style with the .css() method instead of in the tag allowed me to remove it later.
18

I think you can also do:

$('#element').css('background-color', '');

That's what I used to do a long time ago for the display property in plain-old-javascript to show/hide a field.

Comments

5

Try this:

$('#element').css('background-color', 'inherit');

2 Comments

Inherit is unfortunately not the behavior I'm looking for: "the property takes the same computed value as the property for the element's parent" from w3.org/TR/CSS2/cascade.html
More likely 'initial' than 'inherit'. 'Inherit' adapts from the parent, 'Initial' does what the word says.
5

Actually, the syntax I thought was incorrect (with null) seems to be working -- my selector was just improperly formed, and thus yielding no elements. D'oh!

1 Comment

As of jquery 1.4.3 css(..., null) doesn't work and css(..., '') should be used instead -- bugs.jquery.com/ticket/7233
0

For what it's worth this appears not to work in IE 8 for 'filter,' I had to use this (in fadeIn callback):

$(this).attr('style', $(this).attr('style').replace(/\bfilter:\s*;*/, ''));

Obviously, I had need to remove an empty inline filter declaration so the CSS could take effect; there were other inline rules so I couldn't just remove the style attribute.

Comments

-3

If it can help, I add a problem with double quote :

$('#element').css("border-color", "");

does not work while

$('#element').css('border-color', '');

works

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.