Home >Web Front-end >CSS Tutorial >How to Vertically Stack Overlapping Absolutely Positioned Elements in CSS?
In CSS, the position property can be set to various values, including relative, absolute, and fixed. When an element is positioned absolutely, it is removed from the normal document flow and positioned relative to its nearest positioned ancestor or the viewport. This behavior can lead to elements stacking on top of each other, which may not be the desired effect.
In the following example, the elements with the classes .row and .col are absolutely positioned, causing them to overlap:
body { position: relative; /* Contains absolutely positioned elements */ } .container { position: absolute; } .row { position: relative; } .col1, .col2 { position: absolute; }
To resolve this issue and have the elements stack vertically, we need to specify their heights and ensure that their vertical position is managed correctly.
While it is not ideal to modify the CSS for the elements, a possible solution without removing the position properties is to specify the height of each .row and adjust the top property of the second .row to account for the height of the first .row:
body { /* position: relative; remains unchanged */ } .container { /* position: absolute; remains unchanged */ } .row { position: relative; height: 2em; /* Specify height for vertical stacking */ } .col1, .col2 { /* position: absolute; remains unchanged */ } #row2 { top: 2em; /* Offset to account for the height of #row1 */ }
The above is the detailed content of How to Vertically Stack Overlapping Absolutely Positioned Elements in CSS?. For more information, please follow other related articles on the PHP Chinese website!