I’m trying to place a button above a table cell, here’s what I’ve achieved:
This is the code:
body {
margin: 100px;
}
td {
border: 1px solid black;
padding: 20px;
text-align: center;
vertical-align: middle;
}
td span {
text-align: center;
}
table {
border-collapse: collapse;
}
#btn {
display: block;
margin-left: auto;
margin-right: auto;
position: relative;
height: 20px;
top: -30px;
}
<table>
<tr>
<td>
<button id='btn'>test</button>
<span>Alfreds Futterkiste</span>
</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>
That looks good, I’ve placed the button above a table cell. But here’s one thing bothering me: the text in the first table cell is not vertically aligned. Why? I’ve used vertical-align but it doesn’t work. How to make it work
>Solution :
Detach the btn from the DOM flow with position: absolute so it’s not calc’d in the measurement like so;
body {
margin: 100px;
}
td {
border: 1px solid black;
padding: 20px;
text-align: center;
vertical-align: middle;
}
td span {
text-align: center;
}
table {
border-collapse: collapse;
}
#btn {
height: 20px;
position: absolute;
top: -10px;
left: 50%;
transform: translateX(-50%);
}
.pos-relative {
position: relative;
}
<table>
<tr>
<td class="pos-relative">
<button id='btn'>test</button>
<span>Alfreds Futterkiste</span>
</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>
