Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does CSS code initialize .style properties of DOM objects?

Background:

I created a simple DOM event example: see jsfiddle here.

<div id="squirrel" onmouseover="toggleFloat(this)">
    <p>Click me!</p>
</div>

<script>
    function toggleFloat(ele){
        var current = ele.style.cssFloat;
        console.log("cssFloat: "+current);
        if(current==="left")
            ele.style.cssFloat="right";
        else
            ele.style.cssFloat="left";
    }
</script>

Accompanying css:

#squirrel{
  float:left;
}

Odd behaviour was noticed: In the DOM, the #squirrel's initial value for the cssFloat property was "". (Open the developer console to see this. Or notice that the #squirrel doesn't move until the second event fires.).

My question is: Should the CSS code not have initialized the cssFloat property of the DOM object? ...or any of the style properties for that matter?

like image 342
Andrew Avatar asked Dec 02 '25 17:12

Andrew


2 Answers

The style property of an element represents its inline style (defined with the style attribute).

Those are not modified by the css rules defined in a your css file. The browser computes the final style based on those rules and the inline style.

The final computed style can be retrieved using MDN: Window.getComputedStyle()

You generally should avoid to use inline style attributes. Normally you should try to use class to manipulate the appearance of a certain element. Also the use of the style property to dynamically change the inline style should only be used if there is really no way around it, e.g. if you need to move an element dynamically. You could also read the answer to Inline tags vs. inline css properties for more informations.

like image 127
t.niese Avatar answered Dec 04 '25 05:12

t.niese


CSS never modifies the DOM.

The 'style' attributes in the DOM are merged-with/override the CSS defined in stylesheets.

like image 35
user2864740 Avatar answered Dec 04 '25 05:12

user2864740



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!