m4s0n501

bweaver.net

web design, technology, photography, and other mayhem

bweaver.net header image 2

Left-Align Lists With Margin Bullets

October 25th, 2008

»Use jQuery and CSS to left-align unordered lists and put bullets in the left margin, in both Firefox and IE.

 

Left-align lists with bullets in the margin

Though Firefox allows you to move bullets out of the list’s div, Internet Explorer does not. In IE, bullets are clipped if they are moved out of the box.

However, by including an image at the beginning of the list items, then using CSS to align the remainder of the list item to the left margin works just fine.

Of course, that’s kind of ugly.

Enter jQuery

However, javascript can be used to do this automatically, and jQuery can further simplify this work.

HTML

For the HTML, simply tag the unordered list with a unique classname, in this case, “test”.

<ul class="test">
<li>item 1</li>
<li>item 2</li>
</ul>

Javascript

function styleList( cls, imgwidth, imgsrc ){
	$("ul." + cls + " li")
		.css("list-style-type","none")
		.css("text-indent","-" + imgwidth);
	$("ul." + cls + " li")
		.prepend("<img class=\"listitemimage\"" +
			"src=\"" + imgsrc + "\"/>");
	$("ul." + cls).css("padding","0").css("margin","0");
	$(".listitemimage")
		.css("position","relative")
		.css("left","-" + imgwidth)
		.css("top","-2px");
}
$(document).ready(function(){
	styleList( "test", "9px", "/code/bullet01.gif" );
});

Basically, styleList takes a CSS class name that identifies the unordered lists to style. It sets list padding and margins to 0. Then, for list items, it sets list-style-type to none to remove the default bullet and sets a negative text-indent to compensate for the space taken by the bullet image. To each list item it prepends the bullet image. The .listitemimage class is styled to relative positioning, given a negative left shift equal to the width of the bullet, and bumped up a bit.

Demo

Check out the demo of left-aligned lists and margin bullets.

Tags: web design

Have something to say?

Comments are disabled at bweaver.net for a variety of reasons. However, if you have something relevant or otherwise interesting to say, I do want to hear from you. Fill out the contact form below. When you click Send, your message will be emailed to me. Unless you spam me, I'll probably read it soon.