5

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?

migrated from stackoverflow.com Dec 19 '11 at 6:09

This question came from our site for professional and enthusiast programmers.

9

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

  • 1
    where ( 1 ) { use_CSS_classes() ; } – Dave Jacoby Dec 20 '11 at 3:28
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.

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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.