-2

If i set css "padding-top" property to a value in variable (currentHeight), like here:

jQuery("#page-container").css("padding-top", currentHeight);

It works fine, and i get:

<div id="page-container" style="padding-top: 115px;">
...

But padding-top, has to be important like this:

<div id="page-container" style="padding-top: 115px!important;">
...

If i try to set important, like this:

jQuery('#page-container').css({'padding-top': + currentHeight + '!important'});

Than css property padding-top' is not given to element page-container like here:

<div id="page-container">

How to solove this problem?

Thanks

Martin
  • 5
  • 2
    Does this answer your question? [How to apply !important using .css()?](https://stackoverflow.com/questions/2655925/how-to-apply-important-using-css) – CBroe Oct 30 '20 at 12:30
  • 3
    _"But padding-top, has to be important"_ - Why? jQuery adds the style directly on the element. There should be no need for `!important` – Andreas Oct 30 '20 at 12:40
  • @Andreas the element style wouldn't apply if the stylesheet css is marked !important – Rod911 Oct 30 '20 at 12:45
  • 1
    @Rod911 Yes, but that's just another _"code smell"_. Why would you need `!important` in the first place? – Andreas Oct 30 '20 at 12:45
  • https://vecta.io/blog/definitive-guide-to-css-styling-order – Seabizkit Oct 30 '20 at 12:55
  • @Andreas Because template Stylesheet css is making important: padding-top: 0!important; In this case padding-top, because mobile menu is set to fix. – Martin Oct 30 '20 at 13:04

1 Answers1

3

It's not possible, since jQuery will not understand !important property.

My solution to this would be:

Create a new CSS class

.paddingTop{
  padding-top: 115px !important;
}

and use addClass() instead of css()

jQuery('#page-container').addClass('paddingTop');

jQuery('#page-container').addClass('paddingTop');
.paddingTop{
  padding-top: 115px !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="page-container">
  <h1>Test</h1>
</div>