Search code examples
htmlcsscss-tables

Styling CSS tables where display: table-row is used


I am trying to style a CSS table to draw a grey box around every row, and alternate between grey/white background for each row.

.table_row_line {
  border: 2px solid darkgrey;
  width: 100%;
  height: 100%;
  padding: 5px;
}
<section style="display: table;">
  <header class="table_row_line" style="display: table-row;">
    <div style="display: table-cell;"></div>
    <div style="display: table-cell;"></div>
    <div style="display: table-cell;"></div>
  </header>
  <div style="display: table-row;">
    <div style="display: table-cell;"></div>
    <div style="display: table-cell;"></div>
    <div style="display: table-cell;"></div>
  </div>
</section>

This does nothing to the styling.

I have tried wrapping the header in a div, which will allow me to style it, but it then stops acting like a table and the first header row stops aligning with the main content.

How can I style this css table?


Solution

  • Unless the borders are collapsed, table rows don't have borders, they just hold the table cells (which can have borders) in place.

    Set border-collapse: collapse.

    section {
      border-collapse: collapse;
    }
    
    .table_row_line {
      border: 2px solid darkgrey;
      width: 100%;
      height: 100%;
      padding: 5px;
    }
    <section style="display: table;">
      <header class="table_row_line" style="display: table-row;">
        <div style="display: table-cell;">1</div>
        <div style="display: table-cell;">2</div>
        <div style="display: table-cell;">3</div>
      </header>
      <div style="display: table-row;">
        <div style="display: table-cell;">4</div>
        <div style="display: table-cell;">5</div>
        <div style="display: table-cell;">6</div>
      </div>
    </section>

    (Also consider if display: table is really the right approach, and ask if you would be better off with a real table or with flexbox or grid layout).