When to set width or height on floats

January 31, 2007

Floats that are used as inline elements do not require a specified width attribute in CSS. An inline element will take up only as much width as it needs without forcing the content that comes after it onto a new line. Inline elements include <a>, <strong>, <em>, <span>, <br>, <img>, <input>, etc.

A width must be specified for floated block level elements though, unless you want the block level element to fill up the entire width of its parent container. Block level elements span the entire width of their containing elements and force any content that comes before or after them onto new lines by default. Block level elements include <div>, <ul>, <ol>, <li>, <dl>, <dt>, <dd>, <table>, <p>, <blockquote>, <pre>, <form>, <h1>, <h2>, etc.

A height should be specified for a div that contains only floats, or it will collapse completely. Because floated elements are taken out of the normal flow of a document, a div that contains only floats will act as if it contains no content at all (and therefore collapse).

Advertisements