2

I want to work with CSS styles, so I get the needed info about this HTML

<img src="imagelink" id="IMG" style="margin: 5px 4em 3% 2%;">

by this code

if(window.getComputedStyle){
    style = window.getComputedStyle(dom, null);
    for(var i = 0, l = style.length; i < l; i++){
        var prop = style[i];
        var val = style.getPropertyValue(prop);
        returns[prop] = val; 
    }
    return returns;
}        

Until now, I only work with "px", so all works fine. Now I try to work with the other units and just I get trouble.

Instead of 5px, 4em, 3%, 2%, I receive from the computedStyle recalculate absolute values for "px".

"margin-inline-start": "21.3667px"
"margin-left": "21.3667px"
"margin-right": "48px"​
"margin-top": "5px"

Why is it so and how I can prevent that? I want to work with the kind of unit which is defined in the inline CSS.

Recalculate this won't work, because I cannot see any info in the computedStyle that the original kind was not "px".

Thanks a lot for helping to understand and solving that.

UPDATE

I look around to find a way to get all matching rules for a element (css class, inline-style, @import and @media). But all what i find & read are half-workes or to old and wont work now)...i'm frustrated at this point

Aya Salama
  • 1,458
  • 13
  • 17
mikeD
  • 229
  • 2
  • 11
  • 4
    That's what `getComputedStyle` _means_, the computed value of the style! If you want the style as given instead, use, e.g., `element.style.marginLeft` – Mr Lister Feb 14 '19 at 12:23
  • you mean HTMLElement.style? but not jquery.css() - hat should be computedStyle if i'm right? – mikeD Feb 14 '19 at 13:55
  • HTMLELement.style seems to work only with inline css, how i can handle all styles, and get like in my example the correct unit "em" , "%" instead calculatet pixel? – mikeD Feb 14 '19 at 14:00
  • I thought you only wanted the styles from the attribute only; sorry. Do any of the answers to [Find all CSS rules that apply to an element](https://stackoverflow.com/q/2952667/1016716) help? Or any of the linked questions mentioned there? – Mr Lister Feb 14 '19 at 15:36
  • i think that https://stackoverflow.com/a/37958301/10993949 could be a way, but i dont understand how i should use this code!? – mikeD Feb 14 '19 at 19:13
  • This https://codepen.io/blackjacques/pen/eEvXXV produce a security error if you use css links outside your own domain - how i can solve this? – mikeD Feb 14 '19 at 19:17
  • More straightforward, but still in the future: https://stackoverflow.com/questions/9730612/get-element-css-property-width-height-value-as-it-was-set-in-percent-em-px-et/49144353#49144353 – Kaiido Feb 15 '19 at 04:52
  • @Kaiido interesting, but helps me not for the moment. i go crazy, i could not find a way to gett all css styles for a elemen (class,inline,@import,@media). I look araound and around, mostly only half works or to old.... – mikeD Feb 15 '19 at 05:02

0 Answers0