Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

div leaving space when positioned absolute in td

Tags:

html

css

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.

like image 622
Rekha Avatar asked Dec 22 '17 09:12

Rekha


2 Answers

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>
like image 156
Brett DeWoody Avatar answered Nov 02 '22 14:11

Brett DeWoody


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>
like image 41
FIL Avatar answered Nov 02 '22 14:11

FIL