With relative positioning, an element's box is anchored against its own static box. To be perfectly honest with you, there are not many occasions where you will want to offset an element from itself. Suppose, though, that you want to create an interface for dressing up a paper doll. You might place the paper doll in the center and arrange the various garments around it. When the mouse hovers over the garment, it is displaced from its static box onto the paper doll using relative positioning. This sounds contrived, and it is.
Pretend that the doll is Bernie Sanders and that the garments are various wigs that he wears to appeal to his constituents:
Displacing the wigs so that they appear on Bernie's head will be simpler if they are arranged in a plus sign, which can be accomplished by adding a div
to group the middle row:
The plus sign is centered using a couple of flex containers:
The north wig can be moved down onto Bernie's head by setting its position
to relative
and its top
value to 120 pixels, which means that the box will be push down fully below the static box—which happens to line up perfectly with Bernie's head.
Try changing the ID selector and the offset property to position the east wig. Then the south. And then the west.
Wouldn't it be nice if simply dragging the mouse across a wig would drop it onto Bernie's head? That can be done be adding the suffix :hover
on the selectors:
The :hover
pseudoselector applies its rules only when the mouse is hovered over the selected element. While hover styles seem like a powerful tool, don't make your interface dependent on them. Devices that don't use a mouse, like mobile devices, don't support this pseudoselector.
Notice how all four wigs set their position
properties. Try factoring this out so that the value is assigned in only one ruleset.
Each wig has only one of its edges explicitly anchored relative to its static box. If you don't pin down an edge, then its value is taken from the element's static box. For example, the north wig's top edge is displaced, but its left and right edges stay the same. Its implicit bottom edge is ignored and computed using the the top
value and the image height.