I’m getting into HTML right now and today I’m learning about page layout. I want to understand the algorithm that the browser uses to lay out a web page so that I can better anticipate where a div will show up based upon my HTML.
I understand that:
- There are block-like elements and span-like elements.
- Block-like elements take up as much vertical space as needed and by default all horizontal space.
- If you add float styling or absolute positioning, then a div takes up as much horizontal space as needed or you can optionally set a width value.
- Span-like elements take up only as much space as needed.
Where I begin to become unclear is what happens when I start using the clear:both, or when nested divs are involved.
I think what I’m looking for is a notion of a cursor that the browser uses as it lays out the document. If such a notion exists, then could you explain how it works. Otherwise please point me information that you feel will be helpful.
For the sake of simplicity, assume a simple model for HTML objects – only width and height, nor margins or padding, etc.
I don’t think there is an actual cursor, although browsers may internally use something like that. There are a lot of rules (search for ‘Box Model’, or even better, ‘Visual Formatting Model‘) that determine how pages should be displayed.
You are right that there are blocks and inline elements. Blocks do indeed take up all horizontal space unless specified otherwise. They size vertically, unless specified otherwise. That fact should answer your question about the nested divs too.
As far as I can tell, you do have some basic understanding, which is about right too. But instead of pasting the entire documentation about all (incompatible!) versions of the box model here, I think it’s best to find some information about it, starting on the w3.com website.