6

I have some hidden divs that I show via JavaScript when a button is clicked. Right now, I'm hiding them with by using inline styling (i.e. style="display:none;").

This works, but are there general rules or guidelines to follow to determine if I should use inline styles or styling via stylesheets and class selectors?

Rachel
  • 23,979
  • 16
  • 91
  • 159
chrismealy
  • 181
  • 1
  • 6
  • Possible duplicate of [For web apps (vs web pages) why not put scripts and css inline?](http://programmers.stackexchange.com/questions/240734/for-web-apps-vs-web-pages-why-not-put-scripts-and-css-inline) – gnat May 27 '16 at 15:33

4 Answers4

10

Best Practice is to avoid using in-line styles where possible so Yes I would suggest you use the class="hidden"

Check out this link for more information on best practices with inline styles vs external: http://webdesign.about.com/od/css/a/aa073106.htm

3

Sure, why not? For example:

<html>
   <head>
   <style type="text/css">
   body
   {
   background-color:#d0e4fe;
    }
   .hidden
   {
    display:none;
   }
  p
  {
   font-family:"Times New Roman";
   font-size:20px;
   }
  </style>
 </head>

 <body>

  <div class="hidden">This CSS example is hidden!</div>
  <p>This paragraph is visble.</p>

</body>

2

I like inline-styles while designing in-browser since I don't have to go back and remove selectors that I don't end up using. It's also quicker for me to see what styles are applied to what and from where. I actually have never run into problems leaving them like that for one-off styles (e.g., if I need a custom padding on one specific DIV) until I need to customize these styles for mobile in which case I'll have to remove some so I can override them with my media-queries. But, if I end up using the same set of rules on multiple items I almost always create a class for it. So - in a nut shell, I use them for one-offs that I don't need to override using media queries.

As a disclaimer, this is my opinion based on my years of experience and not necessarily based on best practice. If I'm coming into a project I will always try to use their established best practices, which is typically not to use inline-styles, although they do make my life easier both as the initial developer and as the later maintainer.

Sabrina Gelbart
  • 189
  • 1
  • 6
0

There are inline styles on some markup that you absolutely can't remove, but you need to override what those styles are. This could be markup that is being inserted onto the page from foreign JavaScript or perhaps generated from the bowels of a CMS that you cannot control easily.

we CAN override inline styles directly from the stylesheet. Take this example markup:

HTML

<div style="font-size: 40px;">
The inline styles Example. </div>

We can fight that with this:

CSS

div[style] {
   font-size: 20px !important;
}
Purvi Barot
  • 139
  • 2