How I fixed HTML list items jumping around
September 25, 2014
Does this kind of thing drive you nuts?
I was working on a list of items in HTML. It is a bunch of list items, and the selection is indicated with a border. Every time you change the selection, though, the list jumps around by a few pixels. And it is terrible.
(None of this is particularly insightful to anyone who works on this stuff day to day. But I am brushing off my web skills that haven’t gotten much use for a while, and I was glad I could reason through this problem like I did. Maybe this is useful to someone else too.)
The problem is caused by how the CSS box model works. Border adds to the dimensions of the item. The non-selected items do not have a border, and are thus narrower. When a box appears, the width of the item changes, and the items after it shift right. When a box disappears, the width decreases, and the trailing items shift left.
Annoying. But easy to fix.
Now, it is possible to hack the box model in various ways. I don’t know if there is a box model that would end this jumping around without the modification that I did. My fix is dead simple though: let’s add an invisible border to all the elements. There is no
border-opacity CSS property, but this can easily be done with using RGBA color for the border, instead of the more common hex format. This way, the size of the elements stays fixed, just that the border is visible for the selected one, and transparent for the others, but the border is always there.
The result is much nicer. No more jumping around.
See and play with all the code in the fiddle.