views:

627

answers:

3

Why <div style="width:50%" /> is not rendered in xHTML? If I do <div style="width:50%"> &nbsp; </div> only then it is rendered. Do I miss something? Will min-width help? I use strict xHTML 1.0

Is it possible to fix it with CSS only or I must change html markup?

+6  A: 

Because DIV is not a self-closing element in either XHTML or HTML.

You must pair the opening tag (<div>) with the closing (</div>) .

On the other part of your question:

<div style="width:50%">&nbsp;</div>

<div style="width:50%"></div>

The difference between is that in the first there is a non-breaking space character that fills up the DIV. In the second there is nothing. That is why you will not see anything render on the second version.

Also, XML and XHTML are not the same thing. The latter borrows the convention of self-closing a tag if it's not part of a matching pair.

random
But from XML point of view this tag is completely valid. And it also does not render anything if I do `<div style="width:50%"></div>`
Artem
If you have nothing to render between the tags, nothing will render.
random
you could also try adding `"overflow:hidden;"` to the `style` of the `div` since that would stop it from collapsing when it's empty otherwise.
Jannis
+4  A: 

Allowed self-closing tags in XHTML are the following:

<area />
<base />
<basefont />
<br />
<hr />
<input />
<img />
<link />
<meta />

DIV must have both starting and ending tags.

Nimbuz
Any tag can be self-closing in XHTML. You've confused real XHTML with a compatibility hack that allows sending XHTML as HTML to old browsers.
porneL
+3  A: 

Although a self-closing <div /> should generally be avoided in XHTML (because it won't parse as expected in legacy HTML browsers), this is not actually anything to do with XHTML: it's a layout issue.

<div></div>

is a block element containing no content. Its height is therefore zero; you can't see it.

<div>&nbsp;</div>

is a block element containing one line of text. Its height is equal to the line-height property.

If you want an empty div to have some height, you must say so:

<div style="width: 50%; height: 2em; background: red;"></div>

It is an old IE5 bug that an empty div would still render with height as if it contained a line of text. When you are using a Standards Mode doctype (which you should be regardless of whether you are using HTML or XHTML, Transitional or Strict), you won't see this behaviour.

bobince