htmlcsshtml-table

Display a table inline with <p> text


I am trying to display a table inline within a p element. The result should look similar to this:

             *-----------------*
Text before. | Cell 1 | Cell 2 | Text after.
             *-----------------*

As shown, the table needs to be centered vertically with the text. The table might have multiple rows.

The following works (I am using inline css in this example to simplify the post):

<html lang="en">
<head>
</head>
<body>
    <p>
        Text before.
        <table style="display: inline-block; vertical-align: middle;">
            <tr>
                <td>Cell 1</td>
                <td>Cell 2</td>
            </tr>
        </table>
        Text after.
    </p>
</body>
</html>

HOWEVER, if I add <!DOCTYPE html> to the top of the file, the table appears below the "Text before."

There must be a difference between quirks mode (when the doc type isn't specified) and when the doc type is specified, but I don't know how to resolve it.

Thanks!


Solution

  • You can achieve the same, but need a bit of more css with it. And I think we need to replace the <p> with a <div> tag.

    .inline-container {
      display: inline-block;
      /* Keeps the container inline */
      vertical-align: middle;
      /* Aligns vertically to the middle */
    }
    
    table {
      display: inline-table;
      /* Makes the table display inline */
      vertical-align: middle;
      /* Aligns the table in the middle of the line */
      margin: 0 5px;
      /* Optional: Adds spacing around the table */
    }
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
    </head>
    
    <body>
      <div class="inline-container">
        Text before
        <table>
          <tr>
            <td>Cell 1</td>
            <td>Cell 2</td>
          </tr>
        </table>
        Text after
      </div>
    </body>
    
    </html>