John Smith John Smith - 1 month ago 7
CSS Question

Center Text horizontally through out multiple <td> in table

I have a table that is a timetable.
What I want is if there are two or more of the same tasks come after each other for the border between to go. (This I have done). Also i want the text to be centered in the middle of the table.

See Example for clarification

https://jsfiddle.net/79bs6Lhb/3/

HTML

<table>
<thead>
<tr>
<th>1:00</th>
<th>2:00</th>
<th>3:00</th>
<th>4:00</th>
<th>5:00</th>
<th>6:00</th>
</tr>
</thead>
<tbody>
<tr>
<td>Sleep</td> //Should Only be one "Sleep" and it should be centered through all the "Sleep td"
<td>Sleep</td>
<td>Sleep</td>
<td>Sleep</td>
<td>Sleep</td>
<td>Wake Up</td>

</tr>
</tbody>




CSS

table {
border-collapse: collapse;
}

td {
border: 2px solid grey;
padding: 25px;
text-align: center;
}

th {
border: 2px solid grey;
padding: 25px;
text-align: center;
}


JS

var tds = document.querySelectorAll("td")
for (var o = 0; o < tds.length; o++) {
if ($(tds[o]).next().html() === $(tds[o]).html() && $(tds[o]).prev().html() === $(tds[o]).html()) {
$(tds[o]).css("borderRight", "none");
$(tds[o]).css("borderLeft", "none");
} else if ($(tds[o]).next().html() === $(tds[o]).html()) {
$(tds[o]).css("borderRight", "none");
} else if ($(tds[o]).prev().html() === $(tds[o]).html()) {
$(tds[o]).css("borderLeft", "none");
}
}

Answer

Use colspan.

var tds = document.querySelectorAll("td")
    for (var o = 0; o < tds.length; o++) {
            if ($(tds[o]).next().html() === $(tds[o]).html() && $(tds[o]).prev().html() === $(tds[o]).html()) {
                $(tds[o]).css("borderRight", "none");
                $(tds[o]).css("borderLeft", "none");
            } else if ($(tds[o]).next().html() === $(tds[o]).html()) {
                $(tds[o]).css("borderRight", "none");
            } else if ($(tds[o]).prev().html() === $(tds[o]).html()) {
                $(tds[o]).css("borderLeft", "none");
            }
        }
table {
        border-collapse: collapse;
    }

    td {
        border: 2px solid grey;
        padding: 25px;
        text-align: center;
    }

    th {
        border: 2px solid grey;
        padding: 25px;
        text-align: center;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <thead>
        <tr>
            <th>1:00</th>
            <th>2:00</th>
            <th>3:00</th>
            <th>4:00</th>
            <th>5:00</th>
            <th>6:00</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="5">Sleep</td> //Should Only be one "Sleep" and it should be centered through all the "Sleep td"        
            <td>Wake Up</td>            

        </tr>
    </tbody>

Comments