Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 965
John Avatar asked Nov 11 '08 01:11

John


People also ask

How do I use an image as a sprite tag?

You create a defined area with a <a> with display:block; or <div> and use overflow hidden; to hide overflow and position:relative; . Then you place your <img> image sprite inside absolutely positioned, which is possible since you positioned the parent. Then use :hover on the image to change position.

How do you put a Div over an image?

You need to set relative positioning on the container and then absolute on the inner tag div. The inner tag's absolute positioning will be with respect to the outer relatively positioned div. You don't even need the z-index rule on the tag div.

What is a sprite How is it applied using CSS What is the benefit?

In short: CSS Sprites are a means of combining multiple images into a single image file for use on a website, to help with performance.


1 Answers

Did you try display: inline-block; ?

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

like image 183
Andy Ford Avatar answered Oct 23 '22 10:10

Andy Ford