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?

santa
  • 12,234
  • 49
  • 155
  • 255

3 Answers3

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>
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
3

Do it with a javascript function that way:

myEm[0].style.setProperty('margin', '0', 'important');
Joanvo
  • 5,677
  • 2
  • 25
  • 35
  • 1
    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');`.) – CFitz May 31 '19 at 00:49
0

Here is a handy trick I found on another post:

myEm.attr('style', function(i,s) { return s + 'margin: 0 !important;' });
Community
  • 1
  • 1
Salil Dabholkar
  • 622
  • 3
  • 7