1

У меня есть таблица, в которой <th> имеет colspan, и где границы <th> отмечены черной линией:

<table>
  <thead>
    <th colspan="2">vote 1</th>
    <th colspan="4">vote 2</th>
  </thead>
  <tbody>
    <tr>
      <td>vote1</td>
      <td>vote1</td>
      <td>vote2</td>
      <td>vote2</td>
      <td>vote2</td>
      <td>vote2</td>
    </tr>
  </tbody>
</table>

Мне бы хотелось, чтобы эти границы также отмечались и у <td>, first и last не подходят, если несколько <th> с colspan. Более подробный рисунок таблицы смотрите на рисунке:

введите сюда описание изображения

Мне нужно отметить границы первого и последнего <td> относящегося к родительскому <th>. Таблица генерируется динамически, в зависимости от данных.

8
  • А разметку мы сами должны придумать?
    – Cheg
    8 сен 2017 в 11:21
  • @Cheg, если ты придумаешь больше одного (принципиально разных) вариантов разметки table, я очень удивлюсь.
    – Qwertiy
    8 сен 2017 в 11:24
  • @Cheg если тебе это поможет - я выложил. мне нужно отметить границы td первого и последнего относящегося к родительскому th
    – Andy
    8 сен 2017 в 11:31
  • @Qwertiy я имел ввиду конкретно данную таблицу (сверстанную, с css), на основе которой и нужно решить проблему
    – Cheg
    8 сен 2017 в 11:33
  • @Cheg моя таблица динамически генерируется в зависимости от данных и там используется код серверного языка, чтобы добиться такой красоты, поэтому мне хочется избавиться от условий во вьюхе. Например при создании данной таблицы я проверяю первый элемент в цикле или последний и в зависимости от этого присваиваю класс и css добавляю стиль
    – Andy
    8 сен 2017 в 11:36

2 ответа 2

1

Не смотря на давность вопроса, ответ на него так и не дали. Тем временем, на просторах сети проблема актуальна до сих пор.

После поисков и экспериментов, пришёл к выводу, что самым простым и надёжным решением будет использование псевдоэлемента с абсолютным позиционированием и нужными стилями.

  • Исходим из того, что ячеек-заголовков Vote 1 и Vote 2, группирующих неопределённое количество подзаголовков, всегда два и они всегда крайние справа. Тогда задаём Vote 1 и Vote 2 position: relative;, а псевдоэлементам (::after) в этих ячейках - position: absolute;.
  • Т.к. количество строк заранее неизвестно, то выставляем с запасом минимальную высоту для псевдоэлемента (min-height: 100vh;), при этом обрезаем лишнее с помощью table { overflow: hidden; }.
  • По ширине растягиваем псевдоэлемент на 100%, охватывая таким образом все ячейки находящиеся ниже, которые перекрывает <th colspan="">.
  • Чтобы псевдоэлемент позволял взаимодействовать с содержимым ячеек, добавляем свойство pointer-events: none;.

table {
  border-collapse: collapse;
  box-shadow: 0 0 0px 2px #222;
  font: 14px/1em sans-serif;
  resize: both;
  overflow: hidden;
}
th, td {
  min-width: 2em;
  padding: 4px;
  vertical-align: middle;
}
th { box-shadow: inset 1px -2px 0px 0px #ccc; }
td { box-shadow: inset 1px -1px 0px 0px #ccc; }
td:not(:first-of-type) { text-align: center; }

tr:first-of-type > th:nth-last-of-type(1),
tr:first-of-type > th:nth-last-of-type(2) {
  position: relative;
}
tr:first-of-type > th:nth-last-of-type(1)::after,
tr:first-of-type > th:nth-last-of-type(2)::after {
  content: '';
  position: absolute;
  top: 0; left: 0;
  min-height: 100vh;
  width: 100%;
  box-shadow: inset 3px 0 0px -1px #222;
  pointer-events: none;
}

td button {
  height: 1em;
  width: 1em;
  padding: 0;
  text-align: center;
  vertical-align: middle;
  font: 14px/0.75em sans-serif;
}
<table>
  <thead>
    <tr>
      <th rowspan="2"><input type="search"></th>
      <th rowspan="2">Prop. Rep.</th>
      <th rowspan="2">Meet. Vote Rec'd</th>
      <th rowspan="2">Proxy Rec'd</th>
      <th colspan="2">Vote 1</th>
      <th colspan="4">Vote 2</th>
    </tr>
    <tr>
      <th>Test in 5</th>
      <th>Custom</th>
      <th>yes</th>
      <th>no</th>
      <th>don't know</th>
      <th>Custom</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>14 Elm St</td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><button>+</button></td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><button>+</button></td>
    </tr>
    <tr>
      <td>15 Elm St</td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><button>+</button></td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><button>+</button></td>
    </tr>
  </tbody>
</table>

0

Как вариант можно применить colgroup

table {
  border-collapse: collapse;
  box-shadow: 0 0 0px 2px #222;
  font: 14px/1em sans-serif;
  resize: both;
  overflow: hidden;
}
th, td {
  min-width: 2em;
  padding: 4px;
  vertical-align: middle;
}
th { box-shadow: inset 1px -2px 0px 0px #ccc; }
td { box-shadow: inset 1px -1px 0px 0px #ccc; }

td button {
  height: 1em;
  width: 1em;
  padding: 0;
  text-align: center;
  vertical-align: middle;
  font: 14px/0.75em sans-serif;
}

colgroup {
  border: 2px solid;
}
<table>
  <colgroup>
    <col span="4"/>
  </colgroup>
  <colgroup>
    <col span="2" />
  </colgroup>
  <colgroup>
    <col span="4" />
  </colgroup>
  <thead>
    <tr>
      <th rowspan="2"><input type="search"></th>
      <th rowspan="2">Prop. Rep.</th>
      <th rowspan="2">Meet. Vote Rec'd</th>
      <th rowspan="2">Proxy Rec'd</th>
      <th colspan="2">Vote 1</th>
      <th colspan="4">Vote 2</th>
    </tr>
    <tr>
      <th>Test in 5</th>
      <th>Custom</th>
      <th>yes</th>
      <th>no</th>
      <th>don't know</th>
      <th>Custom</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>14 Elm St</td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><button>+</button></td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><button>+</button></td>
    </tr>
    <tr>
      <td>15 Elm St</td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><button>+</button></td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><input type="checkbox"></td>
      <td><button>+</button></td>
    </tr>
  </tbody>
</table>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.