Jones Joseph
Jones Joseph

Reputation: 4938

Relative positioning a th in html table

This question came to my mind not because i am doing a project or something. It just popped up in my head.

I have read (from some posts on stack overflow) that position:relative does not affect table elements and that top,left,bottom,right wont work.

I tried this and found that it does affect the th element as shown in below snippet in some way. top and left properties actually worked on th.

But one thing isnt so clear about this effect, why is it that the border of the th stayed at its place and only the th migrated??? Any ideas as to why this happens?

I would really like to know if the border could be moved along with the th.

table {
  border-collapse: collapse;
}
th {
  border: 4px solid green;
  position: relative;
  top: 30px;
  left: 30px;
}
<table>
  <tr>
    <th>THIS</th>
  </tr>
</table>

Here is a fiddle

Upvotes: 0

Views: 2554

Answers (2)

Yaser
Yaser

Reputation: 5719

You just need to add display: block; to your th and it gets the position. You cannot position the th alone since it just moves the content.

table {
  border-collapse: collapse;
}
th {
  display: block;
  border: 4px solid green;
  position: relative;
  top: 30px;
  left: 30px;
}
<table>
  <tr>
    <th>THIS</th>
  </tr>
</table>

Upvotes: 0

Farzad Yousefzadeh
Farzad Yousefzadeh

Reputation: 2561

Setting position on tr, th, td elements is not a cross-browser idea. so instead of that, put your content inside a container inside your th element and position relatively that container.

<th><div>THIS</div></th>

And the style would be:

th > div { border: 4px solid green;position: relative;top: 30px;left: 30px; }

Working Fiddle

Upvotes: 2

Related Questions