Set the number of columns to span in HTML


The task we are going to perform in this article is set the number of columns to span in HTML.

When utilizing the <td> element, this is accomplished by using the colspan attribute. As a result, a single table cell can now span multiple columns or cells in width. Let’s jump into the article to know more about colspan attribute.

Colspan Attribute

The number of columns that a cell should span in HTML is specified by the colspan attribute. It enables a single table cell to stretch across many columns or cells. It offers the same features as a spreadsheet program like Excel's "merge cell" function.

Syntax

Following is the syntax for colspan attribute.

<td colspan="number">

Let’s dive into the following examples to understand more about colspan attribute.

Example 1

In the following examples we are using colspan for table.

<!DOCTYPE html>
<html>
<head>
    <style>
       body {
           text-align: center;
           
       }
       table,
       tbody,
       td {
           border: 1px solid black;
           border-collapse: collapse;
           
       }
	</style>
</head>
<body>
   <table>
      <tr>
         <th>NAME</th>
          <th>Amount</th>
      </tr>
      <tr>
          <td>Surya</td>
          <td>143</td>
      </tr>
      <tr>
          <td>Karthik</td>
          <td>420</td>
      </tr>
      <tr>
          <td colspan="2">Total Amount : 563</td>
      </tr>
   </table>
</body>
</html>

When the script gets executed, it will generate an output displaying the table consisting of the data in it given in the script along with a colspan of the total amount on the webpage.

Example 2

let’s look into the following example, where we are using colspan with the <article> tag.

<!DOCTYPE html>
<html>
<head>
   <style>
      article {
          columns: 3;
      }
      h1 {
          column-span: all;
      }
   </style>
</head>
<body>
   <article>
      <h1>spanning all of the columns</h1>
      <p>Mahendra Singh Dhoni is an Indian former professional cricketer who was captain of the Indian national cricket team in limited-overs formats</p>
      <p>Virat Kohli is an Indian international cricketer and former captain of the India national cricket team.He plays for Delhi in domestic cricket</p>
      <p>Hardik Himanshu Pandya is an Indian international cricketer who plays for the India national cricket team at the international level and the Baroda cricket team domestically.</p>
   </article>
</body>
</html>

On running the above script, it will generate an output consisting of text used in the script along with the colspan on the webpage.

Updated on: 16-Dec-2022

278 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements