1

I ran into an issue that I can't quite explain.

I wrote a function in in that function I was adding some inline styles to an element:

myEm.css({"margin":"0", "position":"fixed", "top":"50px", "left":"50px"});

It worked fine, however I noticed that this element already had some margin set in a CSS file and it used !important, so the only way I would be able to overwrite is by changing my code to

myEm.css({"margin":"0 !important", "position":"fixed", "top":"50px", "left":"50px"});

However, when I do that the entire margin attribute is dropped. Seems a bit odd, but after testing I suspect the exclamation mark is a culprit. Do I need to escape it somehow of use an encoded character? What am I missing?

3
  • 1
    You add a CSS style with !important and the CSS class to the element. Commented Nov 21, 2014 at 17:03
  • why setting manually the CSS ? why not create a new CSS rule and apply it when you want ? Commented Nov 21, 2014 at 17:05
  • You can probably see your answer here: stackoverflow.com/questions/2655925/… Commented Nov 21, 2014 at 17:12

3 Answers 3

4

Best way is to create a new CSS style with margin !important and add the CSS to the element.

CSS:

.zeroMargin { margin: 0 !important; }

and then in JS:

myEm.css({"position":"fixed", "top":"50px", "left":"50px"}).addClass('zeroMargin');

Alternatively, You can also do that entirely with JS using cssText

myEm.css("cssText", "margin:0 !important;position:fixed;top:50px;left:50px;"});

This is equivalent to setting the style.cssText property of that element. So you may not need an !important in that case..

To preserve you can use a function like below,

$('#cssTest').css('cssText', function(i, v) {
  return this.style.cssText + ';border-color: blue !important;';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="cssTest" style="border: 1px solid red !important; width: 100px; height: 100px;"></div>

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

Comments

3

Do it with a javascript function that way:

myEm[0].style.setProperty('margin', '0', 'important');

1 Comment

This was the only solution that worked for me when trying to change the CSS of a select2 element. (In my scenario, the command was of the format $('span.select2-selection.select2-selection--single[aria-labelledby="select2-actual_element_id_goes_here-container"]')[0].style.setProperty('border-color', 'red', 'important');.)
0

Here is a handy trick I found on another post:

myEm.attr('style', function(i,s) { return s + 'margin: 0 !important;' });

2 Comments

This will not override other style set on margin attribute, you might end up with two values as margin attribute both set as important!
The question said that the original margin was set through a css file

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.