Add a Custom “Trendy” Border Around Blog Images With CSS & JavaScript

Custom Trendy Border Using JavaScriptOne particular design trend that has caught my attention of late on web development and graphic design blogs is the fancy gray border that surrounds images in blog posts. There are subtle variations of it around the web, which you can see on a number of blogs and tutorial sites.

Sometimes it’s just an image with a solid border and slightly lighter shaded background. Elsewhere it’s a linked image with the same effect, plus a rollover state that changes the color of the border and/or background. And sometimes it’s seen in the ads on a design blog.

It’s a nice, yet simple way to add a little style to an otherwise bland looking image — like any of the bland images on my site! :o)

What if you would like to add a border like this to all the images in your blog posts, but don’t want to go through all your blog posts and edit the HTML for every image reference? In this article I’ll discuss a couple of ways to add a “trendy” gray border to all images in your blog posts.

1. Change the CSS Styles Associated With Those Images

If you’ve set up your blog’s CSS to automatically add styles to images with a specific class name, then it’s quite simple. Just modify the styles associated with that class name, and it’s done. In an ideal situation, you would have thought about this type of thing beforehand and it should not pose a problem.

CSS for Non-Linked Images

img.article_image {
	display: block;
	background: #eaeaea;
	padding: 6px;
	border: solid 1px #d6d6d6;
}

CSS for Linked Images

a.article_image, a.article_image:link, a.article_image:visited {
	background: #eaeaea;
	padding: 6px;
	border: solid 1px #d6d6d6;
	text-align: center;
	display: block;
}

a.article_image:hover, a.article_image:active {
	background: #ddd;
}

a.article_image img {
	display: inline;
	border: none;
	border: solid 1px #d6d6d6;
}

View the demo of the CSS version

No Associated Styles? Use JavaScript

There may be a case where you want to apply the above styles to images or anchor tags that have no classes associated with them. Well, this is a little trickier, but by no means impossible. Let’s assume all your article images are wrapped in <a> tags with no IDs or classes on either tag. Here is some JavaScript code that will hunt down all linked images in your blog posts and apply the necessary class name:

var myLinkCollection = document.getElementsByTagName("a");

for (i = 0; i < myLinkCollection.length; i++) {
	var postClass = myLinkCollection[i].parentNode.parentNode.className;
	var childImageSrc = (myLinkCollection[i].childNodes[0].src) ? myLinkCollection[i].childNodes[0].src : "";
	if (postClass.indexOf("post ") !== -1 && childImageSrc.indexOf(".") !== -1){
		myLinkCollection[i].className = "article_image";
		}
	}

View the demo of the JavaScript version

Explanation of the Code

Here is a rundown of the code above, which is assuming the pages in question that are being edited are blog posts on a WordPress installation:

Line 1 collects all links on the current page and places them in an array called myLinkCollection. Line 3 initiates a for loop that iterates through the "link collection" stored in our variable. For each item in the link collection, we do the following:

  • Create a variable to store the class name of its grandparent element (line 4)
  • Using the ternary operator, create a variable to store either the "src" of its child element, or store nothing if the "src" attribute doesn't exist (line 5)
  • Use the indexOf method to check if the class name value of its grandparent element has the string "post " in it (including the space at the end) and check to see if the src attribute of the child element has a period character in it (line 6)
  • If both the above checks turn out to be positive, the current link is given the appropriate class name, and the styles are applied

Like I said, this code is specific to a WordPress blog post, and it assumes that the images/anchors you want to style are contained inside of paragraph tags inside of the "post" container. In WordPress, every post is wrapped inside of a <div> tag that has numerous classes applied dynamically through the PHP. The first class, unless you've customized it, will be "post". So a typical "post" wrapper will look something like this:

<div class="post hentry category-scripting category-articles" id="post-767">

</div>

Thus, in the JavaScript code, we're searching for the string "post " (with a trailing space) to ensure that the grandparent (anchor inside of a paragraph, inside of a div) has this class. After that is confirmed, then we look at the first child of the anchor and ensure that it has a "src" attribute, which pretty much guarantees it is an image. We also search for the period character just to make sure something is found that is always in an image src attribute. You could feasibly change that to something else like a search for any of the strings "jpg", "png" or "gif", which would be even more specific. For my purposes here, the period was enough as not many HTML elements have a "src" attribute.

Some Random Thoughts on This Method

This tutorial is more of a "theoretical" example, as the code is not necessarily ready to "cut and paste" into your pages. But if the context fits your pages, then it is definitely useable.

This method could be done one of a hundred ways via JavaScript and/or CSS. This is just one way to show you what's possible in dealing with styling class-less HTML elements across an entire website. I realize it can be done a little more simply, maybe by targeting the grandparent element first, then iterating through the links inside of that. I just naturally favor collecting all the links first, then styling according to contextual specifics.

Again I stress that this method is WordPress specific, and assumes that the images are contained inside of anchor tags, and each anchor tag is an immediate child of a paragraph element within the "post" wrapper. So, if the images or anchor tags that you want to style have different contexts, then you would need to modify the code to suit your needs.

This method also assumes that the images/anchors will fill the width of the "post" container minus any padding. In other situations, the images might be a smaller size, so it would be necessary to add a specified width to the anchor element, otherwise the border will be too large.

Is there a WordPress plugin that does something like this? Is there a style associated with embedded WordPress images that would facilitate this? Probably. But I personally hard code the (very few) images that I embed in my posts in my WordPress admin area, so I thought this would be a nice exercise to experiment with contextual styling of elements via JavaScript.

When dealing with "child" and "parent" nodes in JavaScript, keep in mind that in some browsers, white-space is considered a node, so you may get different results in different contexts. In that case you would have to do an object check to ensure that the node in question is not a white-space node.

The JavaScript code works in IE6, IE7, FF3, Chrome 2, and Opera 9 -- within the context I've provided.

10 Responses

  1. lets talk about img:hover now!

  2. tnx a lot! i did it and it looks greeeeeeat! thank you so much one more time!

  3. I was looking for something like this for my blog, I will be sure to try it out! Thanks for the tutorial.

  4. Jake:

    I was looking for something like this for my blog, I will be sure to try it out! Thanks for the tutorial.

  5. I found your blog really interesting in terms of providing information to the relevant users.

  6. Very nice post. We will take some changes on our css! Best regards Hans

  7. Thanks man, with this guide I resolved my css problem.

  8. Jaxinvt:

    My image is displayed differently.How would I put a border around an image that is called using the following line?

    <script language=”JavaScript”> showXThumb(1)</script>

    • It would be best if you don’t insert the image with JS, but if you have to then you’ll have to access the image after its loaded. That can be tough though, because the JS I’ve written probably won’t work.

      If you could set up a demo page, then I can take a look at it, but other than that, I’m not sure what to do if I can’t test it.

  9. thx for tutorials, very useful for me ! ☺

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field. If you use keywords, your comment will be deleted, or your name will be replaced with the alias from your email address. No foul language, please. Thank you for cooperating.

Instructions for code snippets: Wrap inline code in <code> tags; wrap blocks of code in <pre> and <code> tags. When you want your HTML to display on the page in a code snippet inside of <code> tags, make sure you use &lt; and &gt; instead of < and >, otherwise your code will be eaten by pink unicorns.