Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style attribute vs setting ID and external Css

Tags:

css

markup

I understand the concept of keeping all presentational elements outside of the markup and putting them into an external .css file.

I want to get a feel for what types of situations you'd justify use of the style attribute vs setting IDs and external Css.

To this point, I've used the style attribute a lot, I usually use it to specify presentation items specific to that element and anything that is for all elements I pull into an external css file but I'd like to reevaluate my position and make the best choice going forward.

like image 550
Nate Avatar asked Sep 10 '09 04:09

Nate


2 Answers

Use external CSS for static definitions. Use element ID lookups and the style attribute for things that change at run-time or where you need Javascript to set things up because CSS isn't capable of what you want.

A good example of the latter was zebra-striping in jQuery prior to widespread support for CSS 3 selectors:

$(document).ready = function() {
    $("table tr:nth-child(even)").addClass("striped");
});

Today, you can do that in the static CSS, but once upon a time, doing in in Javascript was the best option.

like image 126
Warren Young Avatar answered Oct 19 '22 09:10

Warren Young


I use external stylesheets and the reasons are below:

  1. Maintainability - it's much easier when all my presentation stuff are in one files.
  2. Keeping code DRY - yep, this one again. Before, I used to even use the style attribute to set the display to "block" or "none" interchangeably. Now, I just use a class called "hide" and use that class if something needs to be hidden and remove it if something needs to be shown. In these days of full blown Ajax applications, I keep my code free from repeating such things and it's much more clean.
  3. Helps when you work in a large project setting - in my last workplace, we had a suite of applications that shared the same look and feel. By putting it all in an external stylesheet, including styles that will be invoked after a certain event has occurred, it helped the team to apply consistent UI design to the apps.

I tried to think of reasons of using style attributes, but honestly, I can say I only use it when I am lazy to open up the stylesheet to change something quickly(not too proud of this part, so I try to minimize it)

like image 2
DLS Avatar answered Oct 19 '22 08:10

DLS