Michael Schwartz Michael Schwartz - 2 years ago 76
HTML Question

Is CSS as HTML Attribute Bad Practice?

I see this happening more and more often.

I was always taught to keep html, css and javascript separate (with html linking to the sources/scripts of course).

I understand sometimes if you're sending an email then using the

style attribute
in html is sometimes ok and preferred.

However when constructing a website, or application is it considered bad practice to use the

<div style="margin: 0 auto; width: 114px; height: 32px; text-align: center; font-family: arial; padding: 25px; border-radius: 50px; line-height: 32px; background: rgb(46, 154, 255);">Hello world</div>

Answer Source

Yes, it is bad practice. Here are a few reasons:

  • You cannot reuse css code if it is inline (it only applies to the element it is on) so you land up writing extra code that does the same thing (e.g. you have two paragraphs of text that need to be styled the same - if you use the style attritibute you now have to copy and paste the style for each paragraph.)
  • Your code will be harder/impossible to maintain - imagine if you had to change the font on your page. If it is declared inline like this it means going to each place to find and change the code.
  • You cannot easily override the CSS styles. Properties that are declared inline have the second highest priority. The only way to override a property declared inline in a CSS stylesheet is by using the !important keyword.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download