Search code examples
htmlcssjspstruts2

How to combine JSP fragments into seamless table regardless of ordering


I have multiple JSPs that each contains one or more tables.

fragment1.jsp:

<table class="foo">
  <tr>
    <td>stuff</td> <td>stuff2</td>
  </tr>
</table>

fragment2.jsp:

<table class="foo">
  <tr>
    <td>more stuff</td> <td>more stuff2</td>
  </tr>
</table>

<table class="bar">
  <tr>
    <td>whatever</td>
  </tr>
</table>

They are used by wrappers in different configurations:

wrapper1.jsp:

<s:include value="fragment1.jsp" />
<s:include value="fragment2.jsp" />

wrapper2.jsp:

<s:include value="fragment2.jsp" />

If fragment2.jsp comes after fragment1.jsp, I want these two tables to have no margin between them and appear as one table. However, if either one is alone, I want them to be formatted normally as "foo" tables are styled.

Is there a way to indicate this styling preference in some way such that the two "foo" tables will appear as a single table when adjacent, but otherwise style themselves normally?

I am somewhat new to Struts/JSP and dealing with some kludged legacy code, so please help me to understand if this problem would be better solved through another approach.


Solution

  • It is actually possible with CSS only, without JavaScript and without changing the HTML.

    A full screen demo is worth a thousand words...

    Basically, you need to use border-collapse: collapse; and specify the following settings:

    1. When the table is alone, all the borders and margins normally set:

      table {
          border-collapse : collapse;
                   border : 4px solid black;
               margin-top : 20px;
            margin-bottom : 20px;
      }
      
    2. When the table is adjacent to one or more other tables:

      • If it's not the first, remove margin-top and border-top:

        table + table {
            margin-top : 0;
            border-top : none;
        }
        
      • If it's not the last: remove margin-bottom and border-bottom:

        table:not(:last-child) {
            border-bottom : none;
            margin-bottom : 0;
        }
        

    Also ensure to avoid setting a border on the last <tr> of each table:

    tr:not(:last-child) {
        border: 1px solid silver;
    }