Context: I’ve my computer practicals day after tomorrow and this was a practice question sir gave to us today which I’m unable to solve despite spending a lot of time trying to debug the program.
Following is the image of table which I’ve to make using the ‘table’ element of HTML:-
This is my best attempt to create this table but it isn’t giving the desired output:-
<html>
<head>
<title> HTML Practice </title>
</head>
<body>
<table border = 1>
<tr>
<td colspan = "4" align = center> A </td>
</tr>
<tr>
<td colspan = "2" align = center> B </td>
<td colspan = "2" align = center> C </td>
</tr>
<tr>
<td> D </td>
<td colspan = "2" align = center> E </td>
<td> F </td>
</tr>
</table>
</body>
</html>
<html>
<head>
<title> HTML Practice </title>
<style>
table, td {
border: 1px solid;
border-collapse: collapse;
}
td {
text-align: center;
}
col {
width: 3em;
}
</style>
</head>
<body>
<table>
<colgroup>
<col>
<col>
<col>
<col>
</colgroup>
<tr>
<td colspan="4"> A </td>
</tr>
<tr>
<td colspan="2"> B </td>
<td colspan="2"> C </td>
</tr>
<tr>
<td> D </td>
<td colspan="2"> E </td>
<td> F </td>
</tr>
</table>
</body>
</html>
To explain:
HTML (well browsers) do a REALLY bad job of predicting what “comes next” when dealing with tables and spans… In this case, previous rows do their best to conserve space and essentially layout “to the left”.
The simple trick in this case is the magic of the <colgroup> and <col> tags… This “hints” the table to know how many columns are in the layout and makes it easier for the browser to interpret what your colspan’s are doing.
Coupled with this is giving the <col> a width - otherwise again it tries to conserve space and you’ll end up with wonky results.
If you’re not familiar with css and the <style> tag then perhaps read up a little on the concepts - there are other (and better) ways to do this but this solution is nice and compact and simple.