Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Place a button above a table cell and vertically align the text in the cell

I’m trying to place a button above a table cell, here’s what I’ve achieved:

enter image description here

This is the code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading