Sunday, November 13, 2011

Aligning an HTML DIV Inside Another One

Across different projects, I have found people taking CSS shortcuts for translating the Photoshopped design templates into HTML. Back in the days, layout used to be all Table based and it was kind of straight forward to fit everything into grid cells. However, with CSS styling the extra flexibility to put elements in any arbitrary layout came extra responsibility - to make sure things still align nicely while being fluid to accommodate different screen resolutions and form factors.

Aligning the child div in red inside a parent div in green using CSS

Here's a quick and dead simple example to create CSS alignment for a div inside another one!

Pro Tip: Use position:relative for the parent div and position:absolute for the child div.

This will make sure the parent is positioned relatively to other elements in the page. However, the absolutely positioned child can be positioned anywhere inside the parent without making the whole layout fixed.