Most of CSS is fairly straightforward to learn. Tweaking fonts and colors and sizes of boxes: easy. CSS positioning: not so straightforward. In fact, it can be damn frustrating. The properties of display, position, and float-- and the interaction between them-- is relatively complex. Even playing with the properties doesn't necessarily impart clear and total understanding. In this blog post, I hope to clear up some of the confusion surrounding display:block, display:inline, and display:inline-blocks. (For a far more complete explanation of CSS positioning, please consult these two excellent articles: Understanding CSS Positioning Part I and Understanding CSS Positioning Part II.)
Let's start with:
display: block;
An element with the above CSS rule will act like a bully. The element will prevent any other element from being on the same horizontal row, or "line". It will hog that thing up completely: the block bully! The element's width and height can be set by CSS, overriding any natural width or height set by its contents.
Below is how 3 DIVs, all with display:block, behave. Note that I have set the width larger than its content.
display: inline;
An element with the above CSS rule, on the other hand, plays nice, like a friend. It will sit next to other elements on the same horizontal row, or "line", provided it too is display:inline and there is enough width left. If there isn't enough width left on the horizontal row, the element will wrap down to the next horizontal row. The width and height are always set by its contents. An element with display:inline will ignore any dimensions specified in the CSS.
Below is how 3 DIVs, all with display:inline, behave. Note that the size of the DIVs conform to the content-- no more or less.
display: inline-block;
An element with the above CSS rules is a combination of display:inline and display:block. Like display:inline, it will be friendly and sit next to other elements on the horizontal row, or "line". Like display:block, its size an be altered--width, height, margin, and padding can be explicitly set in CSS.
Below is how 3 DIVs, all with display:inline-block, behave. Note the DIVs' customized dimensions.