Having seen advice seemingly change over the years regarding use of empty DIVs (ie.
<DIV CLASS="somediv"></DIV>) I'm confused as to the current thinking over whether or not to use
when a DIV will have no inner HTML.
I can find no definitive confirmation over whether we can rely on all modern browsers to display background color and image correctly at the specified width & height when there is no inner HTML, so I'm thinking maybe we can't rely on it - yet it's such a seemingly basic area.
I have even seen suggestions that empty DIVs should never be used - but do specs really state it is 'wrong' to have empty DIVs, or is it just unreliable? (I've tried finding reference to them, but maybe I'm using the wrong terms).
To illustrate, here are 5 areas where I would normally use an empty DIV, in the absence of any recommended alternative:
- as a placeholder for content which will subsequently be fetched by XHR calls
- as a way to manually create space in a layout
- where an image is defined in CSS (as a background image, but will effectively be foreground)
- where the text will come from the CSS using
- where CSS is used to display graph bars etc using solid background color
Maybe there are different answers for each of these, which might explain the complexity over this issue.
I have, of course, tried discovering already, but for example the SO question Is necessary to show an empty <div>? suggests to me there is a huge amount of "IMHO", "probably", "seems to work" in this area. I would expect that by now that some official consensus has been reached on best practice.
So.. should I use
and if so should I set font-size to the same as the smaller of DIV width/height to ensure that space is filled in all browsers? Are there any other CSS tricks to ensure this will work in all browsers?
The browser is not going to discard or forget your container just because it does not have any contents (yet).
If you want the container to have a specific placeholder shape, then you might give it
width and make sure it's
If you are still unsure, you can fill it with a
spacer.gif/png without padding and margin.
This recipe can be found in it's original form on Stack Over Flow.