I've always found CSS positioning with both float
and position: absolute/relative
hard to work with. I want to introduce to you an alternative way borrowed from the World of Warcraft Interface: Anchors.
Anchor
The concept is extremely simple. You can tell where you want the element to be, relative to another. For example, top left
of this blog's main content is 10px right
relative to the top right
of the menu.
<frame name="Content"> <anchor point="TOP LEFT" relativeTo="Menu" relativePoint="TOP RIGHT" x="10" /> </frame> |
- Allowed points:
TOP LEFT , TOP , TOP RIGHT
LEFT , CENTER , RIGHT
BOTTOM LEFT , BOTTOM , BOTTOM RIGHT - Default Values:
point, relativePoint
:TOP LEFT
.relativeTo
: Parent of the element.x
,y
: 0.
Demo
I've made a quick implementation of this behavior in HTML using data-attribute
. Check the Javascript tab to see the 35 lines of CoffeeScript that makes the following code work:
<!-- In order to put the sidebar centered at the right of the frame: Sidebar.left = Frame.right --> <div id="sidebar" data-anchor="left, #frame, right"></div> <!-- In order to put the chat at the top right of the screen: Chat.topRight = HTML.topRight + {x: -10, y: 10} --> <div id="chat" data-anchor="top right, html, top right, -10, 10"></div> |
Limitations
Static
The current code works well for static elements. As there isn't any event for DOM move/resize, the position will not be updated if anything moves 🙁
It might be possible to achieve the same effect by setting properly the position: absolute/relative
and top/bottom/right/left
CSS properties. I'd be really interested to know if you try to tackle this challenge 🙂
CSS Attribute
It would be more semantically correct to add an anchor
CSS attribute instead of an HTML data attribute. However, it's not possible to access the value of a custom CSS property.
#sidebar { anchor: bottom left #frame top right 10px 0; } |
Multiple Anchors
World of Warcraft supports multiple anchors. For example if you anchor both the left and right sides, then the width of the element is going to be updated accordingly.