Positioning of elements in CSS is one of the harder things to fully understand to those new to creating layouts. In some cases no positioning declarations are needed at all to achieve the desired layout but when they are, getting it right can be a little confusing.
In this article I hope to provide an example that not only explains absolute positioning but can be used in your own layouts where you may otherwise have been struggling. While I’ll touch on the theory behind absolute positioning, I’ll leave a detail explanation to this excellent article from Steven Bradley which I would strongly urge you to read, even if you think you’ve got a good grasp on CSS positioning.
Positioning a ‘buy now’ tag over a div or image
The idea here is to position a small tag overlaying the top right of a sibling element. Let’s imagine we have a book we’re promoting and we’d like to add a promotional tag over an image of the book cover.
Let’s start with some basic markup and styling:
All the elements we need are there, but the tag is sitting above the book cover, rather than overlapping it as we want.
Absolutely position the promo-tag
If no elements within the document have defined positions they work against the document itself which is effectively set to position: static. This follows the ‘normal document flow’ and is defined by the box model.
We need to add a position declaration to the promotional tag to put it in a position not dictated by the normal flow – position: absolute will give us the ability to place the tag exactly where we want by taking it outside of the flow completely. We know we want the tag overlaying the top right of the book cover so let’s give it a position of right: 0;
This says; absolutely position the element 0 pixels from the right.
How does that look?
Not great. The promotional tag is doing exactly what we’ve told it too but not what we want, so what are we missing?
The ‘Cascading’ in ‘CSS’ explains exactly what’s going on here. We’ve told the promotional tag to be absolutely positioned but we haven’t specified what that’s in relation too, so the browsers will assume it’s the document itself.
We’ll need to assign a position: relative declaration to the parent element, in this case ‘book’.
This tells the browser that child elements of ‘book’ should be positioned relative to it, rather than the document if they have any position declaration themselves. It also tells the browsers to relatively position ‘book’ to its parent – in our example that’s body but in more complex layouts that will differ.
How does that look?
So, to recap:
- Buy-tag is set to be positioned exactly where told, ignoring the normal flow.
- Book has the position: relative declaration, ensuring child elements are positioned relative to it rather than the document.