Бесшовное выравнивание фоновых изображений?

Я хотел бы выделить некоторые ячейки в таблице, заштриховав их.

Если две ячейки с одинаковым узором расположены рядом друг с другом, узор должен плавно покрывать обе ячейки.

table.demo {
  border: 1px solid blue;
  border-collapse: separate;
  border-spacing: 0;
  table-layout: fixed;
  text-align: center;
  width: 100%;
}

table.demo td {
  height: 100px;
}

table.demo td.stripes {
  /* Using  background-attachment: fixed;  is _not_ the desired solution, because the background no longer scrolls alogn with the table. */
  /* background-attachment: fixed; */

  background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAAFCAYAAABmWJ3mAAAAIElEQVQImWNggIKOjo7/HR0d/xmQAbIAnI2hCocYYQAATEQPi+UvdB4AAAAASUVORK5CYII=);
}

table.demo td.B { background-color: #ffe; }
table.demo td.C { background-color: #efe; }
table.demo td.E { background-color: #eef; }
table.demo td.F { background-color: #fee; }
<table class = "demo">
  <tr>
    <td class = "stripes A">A</td>
    <td class = "stripes B">B</td>
    <td class = "stripes C">C</td>
  </tr>
  <tr>
    <td class = "stripes D">D</td>
    <td class = "stripes E">E</td>
    <td class = "stripes F">F</td>
  </tr>
  <tr>
    <td class = "stripes G">G</td>
    <td>H</td>
    <td class = "stripes I">I</td>
  </tr>
</table>

Детали зависят от размера области предварительного просмотра, поэтому вам, возможно, придется увеличить или уменьшить окно браузера, чтобы увидеть проблему. Вот увеличенный скриншот места пересечения четырех ячеек, демонстрирующий проблему:

Желаемый результат и цель этого вопроса:

Уже пробовал:

  • Использование background-attachment: fixed; вроде бы решает проблему, но тогда фоновое изображение фиксируется в начале координат области просмотра, то есть перестает прокручиваться вместе с таблицей.

  • Применение фонового изображения к элементу <table> не помогает, поскольку оно охватывает все ячейки, а не только индивидуально выбранные.

Таким образом, вопрос в том, как можно добиться того же плавного выравнивания, но сохранить начало координат фиксированным к <body>, <table> элементу или чему-либо еще, чтобы штриховки прокручивались вместе с остальным содержимым страницы.

🤔 А знаете ли вы, что...
HTML5 предоставляет более широкие возможности для работы с мультимедиа, включая аудио и видео без использования плагинов.


1
63
2

Ответы:

Вот подходящее решение.

Add background-position: center bottom;

Добавление отступов также в:table.demo td:height:100px; padding:10px;

table.demo {
  border: 1px solid blue;
  border-collapse: separate;
  border-spacing: 0;
  table-layout: fixed;
  text-align: center;
  width: 100%;
}

table.demo td {
  height: 100px;
  padding:10px;
}

table.demo td.stripes {
  /* Using  background-attachment: fixed;  is _not_ the desired solution, because the background no longer scrolls alogn with the table. */
  /* background-attachment: fixed; */

  background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAAFCAYAAABmWJ3mAAAAIElEQVQImWNggIKOjo7/HR0d/xmQAbIAnI2hCocYYQAATEQPi+UvdB4AAAAASUVORK5CYII=);
  background-position: center bottom;
}

table.demo td.B { background-color: #ffe; }
table.demo td.C { background-color: #efe; }
table.demo td.E { background-color: #eef; }
table.demo td.F { background-color: #fee; }
<table class = "demo">
      <tr>
        <td class = "stripes A">A</td>
        <td class = "stripes B">B</td>
        <td class = "stripes C">C</td>
      </tr>
      <tr>
        <td class = "stripes D">D</td>
        <td class = "stripes E">E</td>
        <td class = "stripes F">F</td>
      </tr>
      <tr>
        <td class = "stripes G">G</td>
        <td>H</td>
        <td class = "stripes I">I</td>
      </tr>
    </table>

Спасибо.


Решено

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

table.demo {
  border: 1px solid blue;
  border-collapse: separate;
  border-spacing: 0;
  table-layout: fixed;
  text-align: center;
  width: 100%;
  position: relative; /* relative here */
  z-index: 0;
}

table.demo td {
  height: 100px;
  clip-path: inset(0); /* this is important */
}

/* the background */
table.demo td.stripes:before {
  content:"";
  position: absolute;
  z-index: -1;
  inset: 0; 
  background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAAFCAYAAABmWJ3mAAAAIElEQVQImWNggIKOjo7/HR0d/xmQAbIAnI2hCocYYQAATEQPi+UvdB4AAAAASUVORK5CYII=);
}
/**/

table.demo td.B { background-color: #ffe; }
table.demo td.C { background-color: #efe; }
table.demo td.E { background-color: #eef; }
table.demo td.F { background-color: #fee; }
<table class = "demo">
  <tr>
    <td class = "stripes A">A</td>
    <td class = "stripes B">B</td>
    <td class = "stripes C">C</td>
  </tr>
  <tr>
    <td class = "stripes D">D</td>
    <td class = "stripes E">E</td>
    <td class = "stripes F">F</td>
  </tr>
  <tr>
    <td class = "stripes G">G</td>
    <td>H</td>
    <td class = "stripes I">I</td>
  </tr>
</table>