How can I make a DIV behave like an IMG for use as a CSS sprite?

John picture John · Nov 11, 2008 · Viewed 10.3k times · Source

I have written code that automatically creates CSS sprites based on the IMG tags in a page and replaces them with DIV's with (what I thought was) appropriate CSS to position the sprite image as a background letting the appropriate part show through -- the problem is that I cannot get DIVs to behave as drop in replacements for IMGs.

If I leave the default 'display' value set to 'block' then if the original IMG was positioned at the end of some text, the replacement DIV will jump down to the next line after text (which of course is what I would expect something with display: block to do).

If I change the 'display' to inline, then the DIV stays on the same line as the text but it ignores the 'width' and 'height' I have set and collapses. I've tried putting  's inside the DIV but it then only takes up enough width to contain the nbsp.

I've tried experimenting with setting display to all possible values (including the "obscure" ones like 'table-row', 'run-in', 'compact', etc) but all with no luck. Is it even possible to create a DIV with the same layout behavior as an IMG?

I am open to having something more complicated than just a single DIV, however I've tried the obvious things there (one DIV inside another where the inner DIV is set to display: block with the outer set to display: inline) but I haven't found a combination there that works either.

There are always specific things I can do outside of the replaced IMG/DIV to get the layout I want, but my goal is to have a generic auto-CSS-sprite mechanism that works regardless of the rest of the HTML.

Answer

Andy Ford picture Andy Ford · Nov 11, 2008

Did you try display: inline-block; ?

you may have to also use display: -moz-inline-block; for firefox2