Recently while working on our final project, my partner and I ran into an issue involving the positioning of courses on a schedule. We were trying to figure out a way to place elements (courses) on top of another element (the schedule). Naturally on our way to a solution, we stumbled upon absolute positioning. Using this we were able to place the courses in their correct positions on the schedule.
Even though that solution seemed to work, there was something about it that didn’t sit right with me. For whatever reason, the thought of using an absolute position on the page to place elements on another element just did not seem like a smart thing to do. What would happen if I added elements above the table?
Because the table uses the default position, its placement is based on its order in relation to other elements. However, the courses are using an absolute position relative to the page.
The solution to this is relatively simple, but not necessarily one of the most obvious solutions for those who are new to CSS.
CSS Positioning Blog
In the blog CSS Positioning: A Comprehensive Look, Louis Lazaris discusses the main types of positions used in CSS’s position property. The positions are:
- static – positions the element statically, following the normal flow based on its order in relation to other elements, typically unnecessary.
- relative – behaves the same way as a static element, except that if you give it a positioning attribute, such as: “left: 20px;”, it will be offset 20px left from its original spot.
- absolute – causes the element to be completely removed the the document’s normal flow, no longer interacting with other elements. Absolute elements are positioned relative to the page, or to its parent assuming its parent is relatively positioned.
- fixed – behaves similarly to absolute elements, however it won’t move when the document is scrolled or relatively to its parent element.
The key part of this is that absolutely positioned elements can be changed by added a relatively positioned element as its parent. Thus the simple solution to our problem was just to change the schedule (or table) to use a relative position, even though we weren’t making any changes to its position visually.
Not only does this change where the elements are positioned relative to, it also makes it so that if I were to set the width or height of the course’s container using a percentage instead of pixels, it would be relative to the size of the schedule instead of the page.
The reason I chose this blog was because it contained exactly what I was looking for: a way to place absolutely positioned elements relative to its parent.
Source: http://blog.teamtreehouse.com/css-positioning
From the blog CS@Worcester – Andy Pham by apham1 and used with permission of the author. All other rights reserved by the author.