JNat
JNat

Reputation: 1496

Changing inline style vs. changing external stylesheet style using JS

What are the benefits of changing particular bits of style inline in the HTML or changing it from an external stylesheet using Javascript?

For instance, this post explains how one can accomplish changing styles from an external stylesheet. However, the process seems to be much more complicated than changing it inline, and it also refers there may be cross-browser problems. However, the post may be outdated (it is 3 years old, and one of the comments says even then it was 4 years old). Is there another more recent way of doing this?

I ask this because I try to keep my HTML and CSS completely separate.
However, is it maybe simpler, in terms of legibility and performance of the code, to simply specify the styles I want to change inline rather than on an external stylesheet?
Are there any best practices in regard to this matter?

Upvotes: 0

Views: 487

Answers (2)

Starscream1984
Starscream1984

Reputation: 3062

When temporarily accessing or modifying an element's style using Javascript, there is no difference involved in whether that style was defined inline or in css - you will get the style that is applied by precedence and Javascript changes will override any declared style.

However, general best practice is to have a separate stylesheet (or maybe several if you intend to have conditional stylesheets for IE9 and below, or to split up lots of styles into manageable chunks)

This method is less complicated when it comes to debugging and changing styles in real time.

With external stylesheets you can change the entire site in seconds by dropping a new .css file in place. You can't do that with inline styles.

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59292

There are no benefits from inline-css except that it will be given more importance.

External css have the benefits of being cached.

However while rendering the below is the order followed.

Inline CSS styles are given more importance than to styles declaredd in <style></style> and styles declared in <style> is given more importance than to styles declared in external css. files.

Inline-css and even <style> is not preferred and is generally bad practice as extra bytes are transmitted over HTTP and they cannot be cached as external css files can be.

Styling using javascript should be just up to adding a class or removing a class or hiding and showing them, to improve the user experience.

Upvotes: 1

Related Questions