1

I have a margin of an element set in the .scss file of my React component:

.element {
    margin: 20px;
}

I want to sum up this value with a value set to margin in inline styles:

<div className={scss.element} style={{ margin: 10px }}>Whatever</div>

The end result should be: margin: 30px

Eduard
  • 8,437
  • 10
  • 42
  • 64
  • 2
    this can't be done using css thus, you could use javascript, otherwise you could put the end value you want i.e. `style={{ margin: 30px }}` inline style which will override the `margin` value coming from `.scss` – Mhd Alaa Alhaj Nov 21 '17 at 10:54

3 Answers3

1

What you need to do is get both the CSS files computed style and the inline style and add them both together

I used the following function to get the CSS files style:

https://stackoverflow.com/a/27527462/5814976

(Thanks Dude! https://stackoverflow.com/users/3894981/dude)

var cssElm = getStyle('.element'), cssVal = cssElm.split('margin:')[1].split(';')[0],

then used the vanilla blah.style to retrieve the inline style (this only fetched the highest ranking style so if you had an !important tag in your CSS file it would just get that again and the end result would be 40px).

inlineVal = elm[0].style.margin,

Then we clean up both of the strings we retrieved (to remove any units that have applied (em, px etc) and then add them together:

totalVal = parseInt(cssVal.replace(/[^0-9.]/g, "")) + parseInt(inlineVal.replace(/[^0-9.]/g, ""));

and lastly reapplied the style to the original element.

elm[0].style.margin = totalVal + 'px';

you can see a working example here:

https://jsfiddle.net/mdhkxhhd/

Sonny Prince
  • 1,094
  • 7
  • 15
0

Try this

function myfns() {

  var x = document.getElementById("mytxt").value

  document.getElementById("p2").style.margin = x + "px";

}
<div id="p2" className="scss.element" style=" margin: 10px ">Whatever</div>
<input type="number" id="mytxt" />
<button onclick="myfns()">Set Margin</button>
Nisal Edu
  • 7,237
  • 4
  • 28
  • 34
0

try this: jsfiddle

var marginStyle=parseInt(document.getElementById("element").style.margin) ;


var marginCss=parseInt($(".element").css("margin"));

var sum=marginStyle+marginCss;
$("p").html( 'Style margin '+marginStyle+'<br> Css margin '+marginCss +'<br>sum '+sum);

$(".element").css("cssText", "margin:"+sum+"px !important;");
Leo
  • 674
  • 5
  • 18