Gravatar implementation with PHP and CSS

Posted Thursday, March 24, 2005

Filed under: , , ,

This weblog is a playground (some might says a battlefield) for me to learn PHP, CSS, etc. This fourth post concerning gravatars is a bit technical because I wanted to contribute implementation tips for all you PHP coders out there.

For the moment I call the following function whenever I want a gravatar displayed; I just started learning OOP and will update that accordingly asap -but the following works.

function gravatar($email) {
$rating = "R"; //Can be G, PG, R or X
$size = "30"; //From 1 to 80 inclusive
$default = ""; //Full URL to a default image if you choose to have one
$border = "f00"; //Hex value (ff0000 or simply f00) without the #
//Now we build the URL for the request...
//...and send it back to whatever called the function
return "<img src=\"$grav_url\" alt=\"\" class=\"gravatar\" />";

Explanation: the function takes an email as argument and returns an img tag with the gravatar ID as a src. Simple isn't it?
And here is a source file with more complete explanation and the most common requests for paste'n go.

Now for some stylin'!
Of course you don't want to just cram the image in the comment, do you? I use a very simple css rule to put them some pix to the left of the comment. Here it is:

.gravatar {position: absolute; left: -35px}

Now that is simple, isn't it? Well, you'll need a little trick to pull this one. See the "position: absolute"? That means exactly that, and if you don't make it somewhat relative it will probably be 35px from the corner of your page -and the whole lot of them gravatars at that! Ugly, to say the least... Fortunately, the answer is just as easy: add a "position: static" to the closest block element containing the image*. Don't worry, that shouldn't destroy anything because that's the default behaviour of any block.
Somebody mentionned the evil nopic box should the gravatar server not answer... I will think of a way to use the background workaround without using the empty gif and update here when I got something that works. Might be a little more twisted though! :-/
We'll probably need dynamic css and this is going to be real dirty... Not impossible but a more than just three lines. Please leave a comment if you're interested in the answer anyway.
* I recomend using blockquote and p, because that's semantically correct, and displays nicely.

Comments disabled because of spammers.

comment #1 On 25/06, David B. wrote :

!!!! thx, this is just what i needed.

Technorati Profile