Absolute Elements' Vertical Overlap: A Solution
In your HTML code, you have defined two rows, #row1 and #row2, with absolute positioning. The issue arises because absolute elements are removed from the normal document flow and stack on top of each other, resulting in overlapped content.
To solve this, we need to understand the purpose and behavior of absolute positioning. By setting an element to position: absolute;, we remove it from the standard flow and position it relative to its closest positioned ancestor.
In your example, .row and .col1, .col2 are absolute elements nested within .container, which is also absolute. However, since all three elements are absolute, they all become independent and overlap.
To resolve this issue, we need to establish a proper positioning hierarchy. We can achieve this by setting .row to relative positioning. This way, .col1 and .col2 will remain absolute, but they will be positioned relative to .row, which is in the document flow.
This change allows #row1 and #row2 to stack vertically, respecting the normal block element behavior. Here's the modified CSS:
body { position:relative; min-height: 2em; width: 100%; } .container {position:absolute;} .row {position:relative;} .col1, .col2 {position: absolute;}
This modification maintains the positioning properties you require while ensuring that #row1 and #row2 are displayed below each other as expected.
The above is the detailed content of How to Prevent Absolute Elements from Overlapping in CSS?. For more information, please follow other related articles on the PHP Chinese website!