Position an element relative to its grandparent
Positioning an element relative to its grandparent by means of CSS only:
HTML code:
<div class="grandparent">
<div class="parent">
<div class="grandchild"></div>
</div>
</div>
CSS code:
/* Styling the look */
.grandparent {position: relative; height: 100%; width: 100%; padding: 50px 30px 30px 30px; outline: 1px #999 solid; outline-offset: -1px; background: #ccc; box-sizing: border-box;}
.grandparent:before {content: "grandparent"; position: absolute; left: 0; top: 0; padding: 10px 0 0 30px;}
.parent {position: relative; height: 100%; width: 75%; padding: 50px 30px 30px 30px; border: 1px #999 solid; background: #ded; box-sizing: border-box;}
.parent:before {content: "parent"; position: absolute; left: 0; top: 0; padding: 10px 0 0 20px;}
.grandchild {right: 0; top: 0; height: 50%; width: 50%; border: 1px #999 solid; background: #fff;}
.grandchild:before {content: "grandchild"; position: absolute; left: 0; top: 0; padding: 10px 0 0 20px;}
/* Positioning the grandchild relative to its grandparent */
.grandparent {transform: rotate(0deg);}
.grandchild {position: fixed;}
Links
- Position element inside absolute parent with respect to grandparent: stackoverflow.com/questions/25768069/position-element-inside-absolute-parent-with-respect-to-grandparent
- Un-fixing Fixed Elements with CSS Transforms: meyerweb.com/eric/thoughts/2011/09/12/un-fixing-fixed-elements-with-css-transforms/
Browser support
- Windows
- Firefox 20.0+
- Google Chrome 36.0+
- Opera 23.0+
- Linux
- Firefox 20.0+
- Google Chrome 36.0+
- Opera 23.0+
More
- CSS centering <hr />
- CSS centering absolutely positioned elements
- CSS centering image
- CSS horizontal and vertical centering. Variant 1
- CSS horizontal and vertical centering. Variant 2
- CSS horizontal and vertical centering. Variant 3
- CSS vertical alignment
- Float bottom
- Vertical centering of an element with variable height in CSS