Div leaving space at absolute position in td

I am trying to understand the absolute position. I have the following code snippet

div#div1 { position: absolute; left: 0; right: 0; height: 100px; border: 1px solid green; background-color: green; width: 100%; } td { position: relative; border: 1px solid blue; height: 18px; width: 100%; } table { width: 100%; } 
 <table> <tr> <td> <div id="div1"> This is a heading with an absolute position </div> </td> </tr> </table> 

I get some extra space at the top due to absolute positioning. When I specify top:0px , it works fine.

Can someone explain why some place was left using only left and right positioning.

+7
html css
source share
3 answers

By default, vertical-align for baseline table cells. The effect of this can be seen in the first <table> below.

This causes the table contents, text, or <div> be placed around the vertical center.

If you want to move the <div> to the beginning, vertical-align: top; will do the trick. Or a top: 0; .

 div#div1 { position: absolute; left: 0; right: 0; height: 100px; border: 1px solid green; background-color: green; width: 100%; box-sizing: border-box; } td { position: relative; border: 1px solid blue; height: 100px; width: 100%; } table { width: 100%; } 
 <!DOCTYPE html> <html> <body> <table> <tr> <td> Some text </td> </tr> </table> <table> <tr> <td> <div id="div1">This is a heading with an absolute position</div> </td> </tr> </table> </body> </html> 
+8
source share

This is because you put the <div> in the <td> .

The base vertical position of the table cell is average.

See an example below:

 div { background-color: yellow; width: 100%; } div#absolute { position: absolute; } div#absolute-top0 { position: absolute; top: 0; } table { width: 100%; } td { border: 1px solid blue; height: 40px; padding: 0; position: relative; width: 100%; } 
 <table> <tr> <td> <div> This is a div <b>without</b> an absolute position. </div> </td> </tr> <tr> <td> <div id="absolute"> This is a div <b>with</b> an absolute position. </div> </td> </tr> <tr> <td> <div id="absolute-top0"> This is a div <b>with</b> an absolute position and top: 0. </div> </td> </tr> </table> 
+3
source share

This is because you indicated the td position here . Change this in absolute too. you will have no place left.

Here => DEMO

 div#div1 { position: absolute; top: 20px; left: 0; right:0; height:100px; border: 1px solid green; background-color:green; width:100%; } td { position:absolute; background:red; height:18px; width:100%; } table { width:100%; } <table> <tr> <td> <div id="div1">This is a heading with an absolute position</div> </td> </tr> 

-one
source share

All Articles