Neal Grosskopf Dot Com A NG Designs Site

Neal Grosskopf Dot Com Return To Neal Grosskopf's Home Page a NG Designs Site

Toolbar

  • Skip To
    • Menu
    • Content
  • Validate
    • HTML
    • CSS
    • WAI
  • Font Size
    • Small
    • Medium
    • Large
    • Extra Large
  • Account
    • Create Account
    • Login

Interact

Navigation

  • Home
  • Interact
    • Blog
    • Message Board
    • Open Links
    • Open Videos
    • Photo Gallery
    • Polls
    • Reviews
    • Geek Speak
  • Designs
    • View All Designs
    • Professional
    • Corporate
    • Templates
    • Personal
    • Club
    • NG Designs
    • Web Guides
  • Files
    • Artwork
    • Wallpapers
    • My File Downloads
  • Extras
    • Bookmarklets
    • The Magic 8-Ball
    • Career Builder RSS Feed Generator
    • Monster.com RSS Feed Generator

A jQuery Tool That Generates External Stylesheets From Your HTML Structure

  • Actions
    • View All
    • View Article Statistics
    • View User Statistics
    • Search
    • Subscribe to RSS Feed

Recent Articles:

  • Tracking Outgoing Links in Google Analytics Using Event Tracking and jQuery
  • Tracking Internal Website Campaigns With Google Analytics and PHP
  • Everything You Need to Know About jQuery's .data() Method
  • Google vs. China: How It Will Affect Web Workers
  • Don't Like The New Facebook Home Page? Fix It With 5 Lines of CSS
View All

Subscribe To Feed
loading Subscribers

I'm On Twitter loading

Jan 17

A jQuery Tool That Generates External Stylesheets From Your HTML Structure

HTML to CSS Tool

My HTML to CSS tool will parse through your HTML structure, pull out IDs, classes and any inline CSS and create a basic stylesheet for you. To see this article in action, feel free to skip right to the live demo >>

I find myself converting Photoshop files to HTML & CSS quite frequently. Whenever I find myself repeating a task I look for ways to make that task more efficient and therefore waste less of my time. One way my time is wasted during this process is when I rip out all of my inline CSS into an external stylesheet (or most likely an embedded stylesheet in the HTML document temporarily). Usually this involves identifying the IDs and class names of all my HTML elements as well as any inline styles I may have applied in the short-term.

Because of this, I set out to write some javascript that would parse my HTML, look for any elements with and ID or class name. The code also pulls out the inline styles and sorts them by property name. Finally, it also builds unordered list's CSS because whenever I have a unordered list within my template, it almost always needs further styling (think, navbar, footer etc.)

Import jQuery

As with any project, I import Google's hosted jQuery library. This will hopefully be cached in a users browser already:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

jQuery Pseudo Code

Below is a quick overview of the jQuery:

//Dim variables //Check in DOM is ready to be used //Select elements with an ID or CLASS //Select unique CLASSES //Create UL-LI placeholder CSS //Extract inline style CSS //Push results to TEXTAREA

Variables

Below are globally scoped variables which are outside the $(document).ready function. output is used for the final CSS. selector is really just a helper variable which can used to narrow the search for IDs and classes. This means you could look for elements only within another element i.e #content [id], #content [class]. Finally tclasses is used to store the names of classes so there are not duplicate class names in the stylesheet.

var output = ""; var selector = ""; var tclasses = new Array();

The rest of the code is wrapped within the $(document).ready function below. This basically checks to see if the DOM is loaded. Next it loops through elements that have an ID or class and finally sends the output to a textarea.

$(document).ready(function(){ $(selector + " [id]," + selector + "[class]").each(function(i){ }); //Code here $("body").append("<textarea id='output'>"+output+"<\/textarea>"); $("#output").css({height: 400, width: 800}); });

Weed Out Duplicate Classes

Next up, the ID/class names are pulled from the element list being looped through. Class names are then added to a global array. Finally since I find myself styling UL and LI elements frequently, I added some code in to create placeholder CSS for these i.e:

#parent ul { } #parent li { }

Here's the code that creates that:

var tmp = "", childOutput = ""; var tid = $(this).attr("id"); var tclass = $(this).attr("class"); var tstyle = $(this).attr("style"); //Avoids adding duplicate CLASSES to stylesheet if(jQuery.inArray(tclass, tclasses) == -1) { //Adds current CLASS to array if(tclass) tclasses.push(tclass); //Adds UL and LI placeholder styles if they are children of a CLASS or ID $(this).children("ul").each(function() { if(tid) { childOutput = "#" + tid; } else { childOutput = "." + tclass; } childOutput = childOutput + " ul\n{\n}\n\n" + childOutput + " li\n{\n}\n\n"; });

Extracting Inline CSS

Next, the inline CSS is extracted from the elements. I'll explain later why this is tricky between different browsers:

if(typeof(tstyle) != "undefined") { properties = new Array(); properties = tstyle.toLowerCase().split(";"); //Raw input for testing //$("#test").html($("textarea").html() + "\n\n" + properties) //Loops through style attribute properties and trims them for ( var i=0, len=properties.length; i

Sending the Results to a Textarea

Finally the results of the above code is dropped in a textarea:

//Creates output depending on if current element is a CLASS or an ID if(tid) { output = output + "#" + tid + "\n{" + tstyle + "\n}\n\n" + childOutput; } else { output = output + "." + tclass + "\n{" + tstyle + "\n}\n\n" + childOutput; }

Browser Variances

I found the inline CSS returned from Javascript could vary by browser, especially when working with CSS shorthand notation. Internet Explorer prefers to seperate out border: 1px solid #000; to the following:

border-bottom: black 1px #000; border-left: black 1px #000; border-right: black 1px #000; border-top: black 1px #000;

While Firefox does the following:

border: 1px solid rgb(0, 0, 0);

Webkit based browsers such as Safari & Google Chrome seem to be more web developer friendly by leaving the original CSS intact:

border: 1px solid #000;

Other Browser Variances

This gets further complicated when using the background property especially in Firefox:

-moz-background-clip: border; -moz-background-inline-policy: continuous; -moz-background-origin: padding; background: rgb(221, 221, 221) none repeat scroll 0% 0%;

Fortunately, Safari and Google Chrome again, keep the original CSS intact:

background-color: #f1f1f1;

Because of this, you may consider using my tool in Google Chrome or Safari as they seem to keep the original code the same.

Check out the final results >>

A Bookmarklet

Finally, I created a Bookmarklet that can be used on any webpage or website on the internet. This means you can add this as a bookmark/favorite and run it on any website.

Thoughts?

So what do you think? Does this look like something that could help you speed up your development time? Leave your thoughts below >

Tags: css, html, jquery ( Add Tag )

Bookmark This Page:
  • Digg loading
  • Delicious loading
  • Re-Tweet loading
  • StumbleUpon loading
  • DZone loading
  • Snipplr
  • Script & Style

Replies:

  • Brett Gilbert
    Brett Gilbert
    #1

    Tue. January 19, 1:25:14 PM

    Wow - this looks great. My colleagues and I were just discussing this idea. I specifically follow this exact process - ill be interested in trying this out on the next project. thanks!

  • A'braham Barakhyahu
    A'braham Barakhyahu
    #2

    Tue. January 19, 1:25:43 PM

    Nice. I have a site that this will be useful for. It's an older site where I hand jammed the styles in at that time to finish it (and I wasn't great with CDs back then). I can use this to speed up creating my stylesheets. Then it's on to restructuring some of the HTML tags. I also see a lot of the elements on a web page as a bunch of lists. :). Thanks again. Try It out tonight.

  • Neal Grosskopf
    Neal Grosskopf
    #3

    Tue. January 19, 6:06:46 PM

    Thanks guys! I was wondering if anybody followed the same process that I do when converting designs to HTML+CSS. Let me know if you run into any trouble using it.

  • Chad Calhoun
    Chad Calhoun
    #4

    Wed. January 20, 7:46:51 AM

    Neal, this is the exact process I go through as well. Great script. When I get some time I think I'll set it up as an Ubiquity command as well.

  • Liam Potter
    Liam Potter
    #5

    Thu. January 21, 7:51:33 AM

    Would it not be easier to start off with a seperate stylesheet and write it as needed?

    In my head I split my design into blocks, like most people, header, navigation, sidebar, content, footer. I then build one block, style it, move onto the next block etc.

    This way, naturally, my css is already organised into a logical structure, and my markup stays clean all the way through the development process, no need to extract css afterwards.

  • Neal Grosskopf
    Neal Grosskopf
    #6

    Thu. January 21, 12:32:50 PM

    Liam, I'm willing to bet most of us have different methods when converting mockups to HTML+CSS. I've always kind of worked from the inside-out. You could also comment out a couple lines from this so that it ignores inline styles. You could then build your HTML first, run this script and create your CSS template automatically.

  • Ben  Shelock
    Ben Shelock
    #7

    Thu. January 21, 6:00:50 PM

    Oh, didn't get it at first. But that's actually really useful. Favourited :)

  • Luis Lohmann
    Luis Lohmann
    #8

    Fri. January 22, 11:07:58 AM

    It's really useful. Sometimes I'm not so careful and start to code a page using inline styles. Then, when it's finally over, I go through the entire page manually extracting the IDs and styles and writing an external CSS.

  • ibrahim Hassan
    ibrahim Hassan
    #9

    Sun. January 24, 3:35:53 AM

    Wonderful and good

    Very nice and useful

    Thank you
    مركز تحميل


Reply:

B U I Link Font Color Edit Preview ?
Characters: 0 Textbox Size: [+] [-]
   

  • New Comment
    #10

    Sat. July 31, 1:24:17 PM

Font Size:

  • A
  • A
  • A
  • A

Search:

Places:

  • Blog
  • Message Board
  • Chat Room
  • Geek Speak
  • Open Videos
  • Reviews
  • Tag Cloud
 

Site Links

Site

  • About
  • Contact Me
  • Site Map
  • Site Search

Interact

  • Blog
  • Geek Speak
  • Message Board
  • Open Links
  • Open Videos
  • Photo Gallery
  • Polls
  • Reviews

Random Stuff

  • Hosting by FatCow
  • © Copyright 2005 - 2010
  • Modified: Friday, July 16, 2010
  • Load Time: 0.04 Seconds

Site Coded And Designed By Neal Grosskopf Using No Crappy CMS Or Themes