Custom article styling

I was over at Chris Coyier’s CSS Tricks watching a tutorial on how to style individual articles. He references Jason Santa-Maria’s site as a great example of this.

He also showed off a neat WordPress plugin that let’s you override any base CSS style information to create a different look for a specific article. I had a textpattern screen open in front of me at the time and thought, that’s easy to do.

As Chris explains in his tutorial we want to be able to create a new style for a particular article. So we need to override any base styles that get loaded. So how do we do that? With a custom field of course.

Create a custom field called “style-override”, make it a text-area

glz_01

NB: I’m using Gerhard Lazu’s glz_custom_fields plugin in this first example. It’s worth every cent and more. It’ll be used here to create a text area custom field which will give us space to write some code although, ultimately, not entirely necessary for this technique to work.

Head on over to the Write tab and you should see a text-area somewhere underneath the Excerpt field:

txp_write_01

So we can enter some CSS styling now:

body {
background-color: red;
}

…but it would be ignored. Textpattern doesn’t know what to do with it.

We know we only want this code to be applied on an individual article basis and that, if we’re good coders, any references to CSS should go in the head of our html.

The code

<head>
<!-- Style Override on a per article basis -->
<style type="text/css" media="screen">
<txp:if_individual_article>
<txp:if_custom_field name="style-override"> 
 <txp:custom_field name="style-override" />
</txp:if_custom_field>
</txp:if_individual_article>
</style>
</head>

If we’re looking at this as an individual article use the CSS from custom field “style-override”.

Whoa there…

But as Chris rightly points out, what if you want to reuse all those styles you’ve lovingly crafted for another post. It doesn’t make sense to copy/paste all that CSS into another article’s custom field. We can reference another CSS file from within textpattern (or externally if you wish. rvm_css is great for this).

Create a new CSS file called “something-specific-to-your-article”

In the custom field simply add the name of your new CSS file:

txp_style_override

The head our code should now look like this:

<head>
<!-- Style Override on a per article basis (external CSS)-->
<txp:if_individual_article>
<txp:if_custom_field name="style-override">
<txp:css format="link" n="<txp:custom_field name="style-override" />" />
</txp:if_custom_field>
</txp:if_individual_article>
</head>

The key line here is:

<txp:css format="link" n="<txp:custom_field name="style-override" />" />

Enjoy folks!

comments powered by Disqus