Search code examples
csscheckboxalignmentcss-tables

Aligning checkbox to center of td styling only checkbox?


I have a table that has particular rows containing checkboxes. I want to have these checkboxes aligned to center of their parent td's. I know that I can achieve that by styling the parent td like that:

td {
    text-align: center;
}

I also know that I can easily achieve that with jQuery, but unfortunately, I cannot use jQuery.

The table is created through .NET and I cannot target the specific columns that contain checkboxes by giving a certain class.

I wonder if there is a way of styling the checkbox itself in order to align it to the center of it's parent td.

Something like:

input[type=checkbox] {
    margin: auto;
}

Solution

  • You could do it by set display: block; and margin: 0 auto; to input[type=checkbox]

    JSFiddle - DEMO

    td {
        width: 100%;
        background: #EEE;
    }
    input[type=checkbox] {
        margin: 0 auto;
        display: block;
    }
    

    Solution 2: - DEMO

    Set display: table; or display: flex; to input[type=checkbox]

    td {
        width: 100%;
        background: #EEE;
    }
    input[type=checkbox] {
        margin: 0 auto;
        display: table;
    }
    

    For More Info:

    What, exactly, is needed for “margin: 0 auto;” to work?