by

Clever CSS Tricks: Debugging HTML and CSS with Generated Content and Pseudo Elements

Just this morning I had a small conundrum where I was trying to debug some HTML and CSS that I had written. Specifically, I was trying to figure out where some of my wrappers were, and how some alt and title attributes were behaving. And then I had an epiphany: you can do this with CSS!

So here’s a quick snippet that you could add to the top of your stylesheet, or could even incorporate into some sort of jQuery plugin.

CSS Debugger Snippet

How it works

We’re taking advantage of generated content, specifically the content style. One of the properties for this style is attr() where you can output the value of a given attribute. Well, that can be any attribute, including an ID or a class.

A small word of caution

In this particular snippet, I use both ::before and ::after. As IE7 doesn’t support :after or :before, and IE8 only supports :after, you will need to tweak this snippet appropriately for Internet Explorer. Take note, too, to use : instead of :: as I don’t think Microsoft decided to distinguish pseudo-classes from pseudo-elements until IE9.

I decided to add just a touch of styling so that the generated content couldn’t be confused with actual content. Feel free to tweak as you see fit.

::before, ::after{
    font-size: .75em;
    padding: 0 1em;
    text-decoration:none;
    position:relative;
    left: -2em;
    }
  ::before{
  color:blue;
  top:-1em;
}
  ::after{
  bottom:-1em;
  color:red;
}
div::before{
    content: attr(id)
  }
div::after{
  content:attr(class)  
}
img::before, a::before{
  content:  attr(alt) attr(title);
  }
img::after, a::after{
  content: attr(src) attr(href);
  }

It’s also a Gist over on github, if you want to fork it.