CSS positioning: position:absolute, position:relative, and positioning elements within other elements

position is a very useful CSS property that gives us very explicit control over where things should appear on the page.
position gives us the ability to move elements to the exact spot - to the pixel - that we’d like to see them. There are two
main types of position that we see most often: position:relative and position:absolute. I’ve created a quick rundown of how position:relative and position:absolute work in the field.

One of the trickier pieces of CSS positioning is figuring out how to position elements absolutely inside of other elements. Instead of using position:relative to slide an element around, then using things like negative margin or other tricks to reset the document layout, you can use position:absolute within a parent element with position:relative set, and you can get that layout you want without needing to reposition any other elements. Here’s a quick rundown:

  • Create a parent element with a style property of position:relative
  • Inside this parent container, place the element that you’d like to absolutely position along with all other elements. Basically, the larger parent will act as a container for all of the other children, or pieces of the layou
  • Since elements are positioned according to their nearest parent element with position, your absolutely positioned element will move to the correct spot inside the larger container while not disrupting the flow of the others.

With position:relative, we can nudge things around, moving smaller elements, especially inline elements, wherever we like.

position:relative and position:absolute are two very important tricks for creating CSS-based layouts, and are especially useful when trying to replicate a mockup or comp design to the pixel. CSS positioning is an extremely useful way to realize even the most complicated layouts and is often a quick way to get layouts right.

Comments are closed.

I'm Reading…
Search This Site

AddThis Feed Button

Need great hosting?

Categories