Reputation:
I am developing html websites. Here is my code:
<html>
<body>
<div style="width:100%;height:50px;z-index:1;"></div>
<div style="width:100px;height:50px;z-index:2;position:relative;top:-50px;"></div>
<div style="width:10px;height:50px;z-index:3;position:relative;top:-100px;"></div>
</body>
</html>
The code here is very simple. I intend to group the 3 elements into one line. However, the spaces under the element at their original position are reserved. How can I remove the white spaces under?
Upvotes: 0
Views: 104
Reputation: 51211
relative
positioning reserves the space where the element originally would have been placed. Use position:absolute
instead. However, absolute positioning works differently. While relative takes coordinates "relative" to the element's original position, absolute takes coordinates relative to the parent* element's position.
*: The nearest ancestor with position other that static or if none is present, the body. In your case it would be the body.
Example:
<html>
<body>
<div style="position:relative">
<div style="width:100%;height:50px;z-index:1;"></div>
<div style="width:100px;height:50px;z-index:2;position:absolute;top:0;"></div>
<div style="width:10px;height:50px;z-index:3;position:absolute;top:0;"></div>
</div>
</body>
</html>
Sidenote: avoid inline styles and your markup is broken - you are missing a <
.
Upvotes: 1
Reputation: 10603
That's because you're using relative positioning. In order for relative positioning to work, the browser has to load the DOM first so it knows the original location of the element, it can then apply the positional values to move it, this means the document will not re-flow around the positioned elements hence your white space. The quickest fix is to wrap your div stack in a relative positioned div
, then apply absolute positioning
<div style="position:relative">
<div style="width:100%;height:50px;z-index:1;"></div>
<div style="width:100px;height:50px;z-index:2;position:absolute;top:-50px;"></div>
<div style="width:100px;height:50px;z-index:2;position:absolute;top:-100px;">/div>
</div>
You'll have to play with the inner div positional values, but that should work for you. The wrapping div with relative position set makes the absolute positioning use that div as the parent, rather than the body element, so in your example it is not required, but in the real world, you'll probably want to do this.
However, i'd consider whether a <ul>
elemnt would be more appropriate in this scenario
Upvotes: 1