Vue.js Checkbox Alignment Issue: Centering Checkboxes Within Table Cells

30 Views Asked by At

m encountering an alignment issue with checkboxes in a Vue.js application. I'm attempting to center the checkboxes within their respective table cells. By default, they appear left-aligned. Upon applying CSS styling to the cell, all the checkboxes unexpectedly align vertically to the center of the leftmost column of the table, rather than staying centered within their cells. How can I resolve this alignment discrepancy?

<tbody>
    <!-- Loop over roles -->
    <template v-for="(characters, role) in categorizedCharacters" :key="role">
        <tr @click="toggleRoleVisibility(role)">
            <td>{{ role }}</td>
            <!-- Placeholder cells for alignment with the header; hidden but keeps the structure -->
            <td v-for="event in state.events" :key="`role-${event.title}-${role}`"></td>
        </tr>
        <!-- Loop over characters within each role -->
        <template v-if="state.roleVisibility[role]" v-for="character in characters" :key="character.name">
            <tr>
                <td>{{ character.name }}</td>
                <!-- Generate a cell for each event -->
                <td v-for="event in state.events" :key="`signup-${event.title}-${character.name}`" class="checkbox-cell">
                    <input type="checkbox" :checked="characterSignedUp(character, event)" />
                </td>
            </tr>
        </template>
    </template>
</tbody>
.checkbox-cell {
    display: flex;
    justify-content: center;
    align-items: center;
}

Before

After

Thanks for any help

1

There are 1 best solutions below

2
Alexander Nenashev On BEST ANSWER

You change display of td thus breaking its table cell layout.

Just select a different way, for example, position the input absolutely or add a wrapper DIV:

td{
  border: 1px solid gray;
  width:100px;
  height:40px;
}
.checkbox-cell{
  position:relative;
}
.checkbox-cell input{
  position: absolute;
  top:50%;
  left:50%;
  margin-top:-6px;
  margin-left:-6px;
}
.checkbox-cell2{
  position:relative;
}
.checkbox-cell2 > div{
  position: absolute;
  inset: 0;
  display:flex;
  align-items: center;
  justify-content: center;
}
<table>
  <tr><td class="checkbox-cell"><input type="checkbox"></td></tr>
</table>

<table>
  <tr><td class="checkbox-cell2"><div><input type="checkbox"></div></td></tr>
</table>