Search code examples
htmlhtml-tablecell

How make a row with different columns in html


My question is that how can I make a row with different columns quantity ? For example I want to have 2 columns in last row in this picture (the portion of each cell must be 50%). Another question that I have is that how can I make text starts from first line in a cell (center cell , in this picture) ?

enter image description here

My code is :

table {
  border: 1px solid black;
  border-collapse: collapse;
  border-spacing: 5px;
}
th,
td {
  padding: 10px;
}
<table style="width:100%" border="1px" cellpadding="5" cellspacing="5" bordercolor="green" bgcolor="yellow" height="500px">
  <caption>web design homework</caption>
  <tr>
    <th colspan="3">My Website</th>
  </tr>
  <tr bgcolor="#77E022" height="20px" align="left">
    <td colspan="3">
      <a href="www.google.com" style="text-decoration:none">home</a> &nbsp;&nbsp;&nbsp; <a href="www.google.com" style="text-decoration:none">products</a> &nbsp;&nbsp;&nbsp; <a href="www.google.com" style="text-decoration:none">contact us</a>
    </td>
  </tr>
  <tr>
    <td width="25%">last post</td>
    <td rowspan="2" width="50%">hello my name is mohammad ghorbani and i am studying computer enginerring in arak</td>
    <td>our friends</td>
  </tr>
  <tr>
    <td>our statics</td>
    <td>24</td>
  </tr>
  <tr>
    <td>our social pages</td>
    <td>about us</td>

  </tr>
</table>


Solution

  • There's two primary answer categories to your question.

    First, the direct answer. Think of your page as a grid. You want enough squares on the grid to be divisible by both 3 and 2. Say, 6. Then use colspan to set each column to the number of grid columns that would be needed -- so, colspan=2 for 3 columns, and colspan=3 for 2 columns.

    <table border=1>
      <tr>
        <td colspan=6>My Website</td>
      </tr>
      <tr>
        <td colspan=6>home, products, contact us</td>
      </tr>
      <tr>
        <td colspan=2 style="width:33%">last post</td>
        <td colspan=2 rowspan=2 style="width:33%">hello my name</td>
        <td colspan=2 style="width:33%">our friends</td>
      </tr>
      <tr>
        <td colspan=2 style="width:33%">our statics</td>
        <td colspan=2 style="width:33%">24</td>
      </tr>
      <tr>
        <td colspan=3 style="width:50%">our social pages</td>
        <td colspan=3 style="width:50%">about us</td>
      </tr>
    </table>
    

    The other answer category is that you should avoid using tables for your layout structure. There's a LOT of Google results for this one, and it's very opinion based, so I'll just say that generally tables should be used for data, css for layouts, and using tables for layouts may be quicker but it's less flexible.