Explain Codes LogoExplain Codes Logo

Absolute position and Overflow:hidden

css
positioning
overflow
css-tricks
Alex KataevbyAlex Kataev·Oct 13, 2024
TLDR
.parent { position: relative; /* The boss div dictating if the child can go outside */ overflow: hidden; /* Sorry, kids, you can't play outside the div */ } .child { position: absolute; /* Like a mischievous child trying to go outside */ top: 50px; left: 50px; /* Coordinates like pirate's secret treasure, arrr! */ }

What happens with the above code is that, while an absolute positioned child is allowed to walk freely, the parent with overflow: hidden and position: relative ensures that as soon as the child tries to take a step outside the parent's boundary, they disappear (get clipped).

Double div method

We can preserve overflow:hidden for the parent and display the entire child by introducing an extra div. This div acts as a buffer and allows positional independence from the parent. Consequently, the overflow of the parent does not affect this div, and the child remains visible, like a clear umbrella protects from rain but keeps things visible.

.parent { position: relative; overflow: hidden; /* Umbrella: deployed. */ } .parent .wrapper { position: absolute; /* The kid gets its own protective bubble. */ } .parent .wrapper .child { position: absolute; /* The kid can walk wherever it wants within its newly found domain. */ top: 50px; left: 50px; }

Into the third dimension

Speaking of z-index, this is your secret weapon, the ‘invisibility cloak’ of sorts for your child div, allowing it to escape unnoticed beyond its parent's boundaries by rendering it over other elements.

Mind the transform and offset

Note: transformations and changes to position of the parent div can affect the offsetParent, and impact the absolute positioning of the child.

Call for backup: JavaScript

When pure CSS can't rescue, JavaScript swoops in to catch the child div from a clipping disaster. Javascript getBoundingClientRect() method is your trusty GPS for pinpointing the child's position accurately.

No boundaries with Body

In drastic scenarios, we can employ body to append the child div. This method is like moving the child to a room with no walls (viewport), bypassing any overflow:hidden restrictions.

The pseudo-elements trick

Pseudo-elements (::before, ::after) that are children of parent div can manage to remain visible, despite overflow: hidden.

Keeping your layout tidy

By introducing a new div with clear:both; after your absolute positioned div, this prevents disrupting the normal flow around the parent.

The gift of examples

Nothing beats a practical demonstration. Check the jsfiddle link to see these concepts in action.