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.

<html>
<head>
<style>
.container{
width: 10%;
height: 10%;
float: left;
background-color: green;
border: 1px solid #00FF 00;
margin: 0.5%;
position: relative;
}
.baby{
width: 50%;
height: 50%;
background-color: red;
position: absolute;
}
.center{
margin: 0 auto;
left: 25%;
}
.right{
left: 50%;
}
.middle {
top: 25%;
}
.bottom {
top: 50%;
}
</style>
</head>
<body>
<div id="top_left" class="container">
<div class="baby top left">
</div>
</div>
<div id="top_center" class="container">
<div class="baby top center">
</div>
</div>
<div id="top_right" class="container">
<div class="baby top right">
</div>
</div>
<div id="middle_left" class="container">
<div class="baby middle left">
</div>
</div>
<div id="middle_center" class="container">
<div class="baby middle center">
</div>
</div>
<div id="middle_center" class="container">
<div class="baby right middle">
</div>
</div>
<div id="bottom_left" class="container">
<div class="baby bottom left">
</div>
</div>
<div id="bottom_center" class="container">
<div class="baby bottom center">
</div>
</div>
<div id="bottom_right" class="container">
<div class="baby bottom right">
</div>
</div>
</body>
</html>
view raw align.html hosted with ❤ by GitHub
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.