HTML - colspan Attribute



The HTML colspan attribute is used to define how many table columns a cell should span or extend.

The value for this attribute must be a non-negative integer. Its default value is 1, and if we assign a value greater than 1000 to this attribute, it is considered as false value and will be set to the default value of 1.

If you assign a negative value to it, it treats it as a false value and will automatically set the default value 1 to it.

Syntax

Following is the syntax for HTML colspan attribute −

<tag colspan = "value"></tag>

Where the value can be any non-negative integer from range 1 to 1000.

Example

In the following example, we are using the colspan attribute with the th tag.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>HTML 'colspan' attribute</title>
   <style>
      table,
      th,
      td {
         border: 1px solid black;
      }
   </style>
</head>
<body>
   <!--HTML 'colspan' attribute-->
   <p>Example of the HTML 'colspan' attribute</p>
   <h2>Students Table</h2>
   <table>
      <tr>
         <th colspan="2">Name</th>
         <th>Roll No</th>
         <th>Gender</th>
      </tr>
      <tr>
         <th>First Name</th>
         <th>Last Name</th>
      </tr>
      <tr>
         <td>Revathi</td>
         <td>Satya</td>
         <td>1</td>
         <td>Female</td>
      </tr>
      <tr>
         <td>Aman</td>
         <td>Kumar</td>
         <td>2</td>
         <td>Male</td>
      </tr>
   </table>
</body>
</html>

On running the above code, the output window will pop up displaying the table filled with data on the webpage.

Example

Considering the another scenario, where we are going to use the colspan attribute with the td tag.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>HTML 'colspan' attribute</title>
   <style>
      table,
      th,
      td {
         border: 1px solid black;
         width: 30%;
      }
   </style>
</head>
<body>
   <!--HTML 'colspan' attribute-->
   <p>Example of the HTML 'colspan' attribute</p>
   <h2>Grocery Bill</h2>
   <table>
      <tr>
         <th>Name</th>
         <th>Price</th>
         <th>GST</th>
      </tr>
      <tr>
         <td>Bread</td>
         <td>50</td>
         <td>5</td>
      </tr>
      <tr>
         <td>Eggs</td>
         <td>180</td>
         <td>10</td>
      </tr>
      <tr>
         <!--colspan with value 2-->
         <td colspan="2">Total price(without GST): 230</td>
         <td>Total GST: 15</td>
      </tr>
      <tr>
         <!--colspan with value 3-->
         <td colspan="3">Total paid price(including GST): 245</td>
      </tr>
   </table>
</body>
</html>

When we run the above code, it will generat an output consisting of the table filled with data displayed on the webpage.

html_attributes_reference.htm
Advertisements