I am trying to understand position absolute. I have the below 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 am getting some extra white space in the top due to positioning absolute.
When I specify top:0px
, it is working fine.
Can someone please explain why some space is left behind when using only left and right positioning.
The default vertical-align
for table cells is baseline
. The effect of this can be seen in the first <table>
below.
This causes the table contents, text or <div>
, to be placed around the vertical center.
If you want to move the <div>
to the top, 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>
It is because you put a <div>
into a <td>
tag.
Base vertical position of a table cell is middle.
See 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With