Floating Elements with CSS

Posted by on December 1, 2011 in CSS, Programming | 0 comments

Floating elements used to be a huge deal when I started developing. What I mean by floating is that when you scroll down the page, the element scrolls with you, always maintaining the same position on your screen. The issue back in the day was that the scripts people offered to float elements down the page were choppy, laggy, and generally not pleasing to look at. Yes the content scrolled with you down the page, but it wasn’t a nice experience.

Now, with css, you can create a seamless floating element that doesn’t jump around or fail to keep up with the scrolling. I will state one exception to this is that the iOS 5 has been reported to have issues and it’s slightly laggy.

The key style to set on your elements is the position. Now there are 4 different types of positions.

  1. Static – This is the default.  You don’t have to set this.  It will just make the element appear where ever the code is placed in the normal rendering of the page.
  2. Absolute – This will make the element stay put inside another element.  You can use this to overlap elements or position them in ways that the normal positioning based off the line height can’t allow you to do.
  3. Relative – This is sort of like static, but if you give it a top/bottom/left/right, it will position it based off where it normally would have been if you didn’t give it a position.  I also use it when I’m nesting different types of positions inside each other.
  4. Fixed – This will make the element stay exactly where it is rendered on the user’s screen, allowing the floating feature.
Now I mentioned that I nest different positions sometimes.  For instance, if you have a div on a page that’s centered.  If you wanted to float a div using the fixed position that’s aligned with the left side of that element, you would need to nest the positions so it renders correctly in the different browsers.  Normally if you just put a fixed position on an element, it will position it’s top/bottom/left/right based off the whole screen, but if you leave the left undefined for instance, it will inherit it from the previous element.  So you can align it to the bottom of the user’s screen, but have it start at the left hand side of your center aligned div.  If you didn’t do this, you’d be stuck trying to figure out an estimate of where that div would render on different sized monitors.
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Comment

Your email address will not be published. Required fields are marked *