Sohan's Blog

Living the Developer's Life

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.


Comments

Sohan
Thanks Scott! Almost invariably the most "hacky" part of any web app can be found in its stylesheet. Hope it changes someday, at least for the apps that I will work on!
Scott Muc
Nice, I too learned about the wonderfulness of parent divs being postion:relative and child divs being postion:absolute when I worked at Radio 3. After the eureka moment positioning didn't seem that hard anymore.