Подтвердить что ты не робот

Чистая css Chessboard с div и без классов или ids, возможно ли это?

У меня есть следующий макет

<div id="chess">
    <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
    <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
    <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
    <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
    <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
    <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
    <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
    <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div>

Можно ли сделать шахматную доску, используя только css и не меняя вышеуказанный html? Это означает, что нет классов или идентификаторов. Я искал идеи, такие как 2 дня. Я попытался с nth-child() и некоторыми вариантами, но не успел.

Мне очень любопытно, можно ли это сделать. Это было дано как задание кому-то.

Так что, пожалуйста, какие-нибудь идеи?

4b9b3361

Ответ 1

Вам не нужно жестко указывать каждый :nth-child(). Здесь один из способов сократить его. Каждый селектор соответствует строке на шахматной доске:

#chess div:nth-child(-2n+8), 
#chess div:nth-child(8) ~ div:nth-child(-2n+15), 
#chess div:nth-child(16) ~ div:nth-child(-2n+24),
#chess div:nth-child(24) ~ div:nth-child(-2n+31),
#chess div:nth-child(32) ~ div:nth-child(-2n+40),
#chess div:nth-child(40) ~ div:nth-child(-2n+47),
#chess div:nth-child(48) ~ div:nth-child(-2n+56),
#chess div:nth-child(56) ~ div:nth-child(-2n+63) {
    background-color: #000;
}

Предварительный просмотр jsFiddle

Ответ 2

Это интересная проблема. Я думаю, что шахматная доска лучше выражается в виде таблицы, а не как сериал, так как программа чтения с экрана будет определять строки и столбцы, где находятся цифры. С таблицей:

table tr:nth-child(odd) td:nth-child(even) {
  background: #000;
}
table tr:nth-child(even) td:nth-child(odd) {
  background: #000;
}

http://jsfiddle.net/9kWJZ/

Ответ 3

В следующем подходе используется тот факт, что шаблон окраски повторяется каждые 16 квадратов (считая сверху слева на нижний правый). Итак, первое правило #chess div:nth-child(16n+1) раскрашивает квадраты 1,17,33 и 49 (другими словами, "первый столбец" ). Это повторяется с дополнительными правилами для всех цветных квадратов от 3 до 16, каждый из которых представляет отдельный столбец.

При заданной разметке не имеет значения, используете ли вы nth-of-type или nth-child, однако с дополнительной разметкой он может, поэтому nth-child является более очевидным выбором.

for(i=0;i<64;i++){chess.appendChild(document.createElement("div"))}
#chess div{
     width:22px;height:22px;border:1px solid black;
     float:left; 
}

#chess div:nth-of-type(16n+16),
#chess div:nth-of-type(16n+14),
#chess div:nth-of-type(16n+12),
#chess div:nth-of-type(16n+10),
#chess div:nth-of-type(16n+7),
#chess div:nth-of-type(16n+5),
#chess div:nth-of-type(16n+3),
#chess div:nth-of-type(16n+1){   
    background-color:black;
}

#chess div:nth-of-type(8n+1){   
    clear:left;
}
<div id="chess"></div>

Ответ 4

В чистом CSS принятый ответ выглядит правильно - однако, если вы хотите сократить его с помощью SCSS, вы можете выполнить некоторые математические операции:

#chess {
  div {
    background: #fff;
    /* even children on odd rows, odd children on even rows */
    @each $offset in 2 4 6 8 9 11 13 15 {
      &:nth-child(16n + #{$offset}) {
        background: #000;
      }
    }
  }
}

Ответ 5

конечно, это можно сделать...

body {
    background-image:
    -moz-linear-gradient(45deg, #000 25%, transparent 25%,transparent 75%, #000 75%, #000 100%),
    -moz-linear-gradient(45deg, #000 25%, transparent 25%,transparent 75%, #000 75%, #000 100%);
    background-image:
    -webkit-linear-gradient(45deg, #000 25%, transparent 25%,transparent 75%, #000 75%, #000 100%),
    -webkit-linear-gradient(45deg, #000 25%, transparent 25%,transparent 75%, #000 75%, #000 100%);
    -moz-background-size:100px 100px;
    background-size:100px 100px;
    -webkit-background-size:101px 101px;
    background-position:0 0, 50px 50px;
}

Ответ 6

Вы не можете использовать nth-child(odd) или nth-child(even) для окраски квадратов, потому что не все "четные" или "четные" квадраты одного цвета. Подсчитав из левого верхнего положения как "1", первые квадраты белых квадратов будут 1, 3, 5, 7. Продолжая во второй строке, белые квадраты будут 10, 12, 14, 16. Третья строка будет вернемся к нечетным числам 17, 19, 21 и 23.

Таким образом, вы можете вручную раскрасить каждый квадрат следующим образом:

#chess {
    /* 8 squares at 30x30px per square */
    width: 240px;
    height:240px;
    background:#000;
}

#chess div {
    width:30px;
    height:30px;
    float:left;
}

#chess div:nth-child(1), /* first row */
#chess div:nth-child(3),
#chess div:nth-child(5),
#chess div:nth-child(7),
#chess div:nth-child(10), /* second row */
#chess div:nth-child(12),
#chess div:nth-child(14),
#chess div:nth-child(16)
/* ... up to 64 ... */
{
    background:#fff;
}

Ответ 7

Я понимаю, что опоздал на игру, и уже есть несколько хороших ответов на этот вопрос.

Я просто хотел бы добавить решение, которое мне кажется простым в управлении при работе с продвинутыми селекторами :nth-child. Это несколько многословно и не так элегантно, как некоторые другие предложения, но мне легко читать и разбираться.

Объединяя псевдо-классы :nth-child вы можете ограничить свой выбор только определенными диапазонами. В псевдокоде это можно выложить как:

:nth-child( start of range ):nth-child( children to select ):nth-child( end of range )

Это может быть использовано для раскраски шахматной доски строка за строкой, как это:

/* Start at 1st square, color odd squares until the 8th */
#chess :nth-child(n+1):nth-child(odd):nth-child(-n+8),

/* Even squares from 9th to 16th */
#chess :nth-child(n+9):nth-child(even):nth-child(-n+16),

/* Odd squares from 17th to 24th */
#chess :nth-child(n+17):nth-child(odd):nth-child(-n+24),

/* Even squares from 25th to 32nd */
#chess :nth-child(n+25):nth-child(even):nth-child(-n+32),

/* Odd squares from 33rd to 40th */
#chess :nth-child(n+33):nth-child(odd):nth-child(-n+40),

/* Even squares from 41st to 48th */
#chess :nth-child(n+41):nth-child(even):nth-child(-n+48),

/* Odd squares from 49th to 56th */
#chess :nth-child(n+49):nth-child(odd):nth-child(-n+56),

/* Even squares from 57th to 64th */
#chess :nth-child(n+57):nth-child(even):nth-child(-n+64) {
    background: #000;
}

#chess {
    width: 320px;
    height: 320px;
    border: 1px solid #000;
}

#chess div {
    float: left;
    width: 40px;
    height: 40px;
    background: #fff;
}

#chess :nth-child(n+1):nth-child(odd):nth-child(-n+8),
#chess :nth-child(n+9):nth-child(even):nth-child(-n+16),
#chess :nth-child(n+17):nth-child(odd):nth-child(-n+24),
#chess :nth-child(n+25):nth-child(even):nth-child(-n+32),
#chess :nth-child(n+33):nth-child(odd):nth-child(-n+40),
#chess :nth-child(n+41):nth-child(even):nth-child(-n+48),
#chess :nth-child(n+49):nth-child(odd):nth-child(-n+56),
#chess :nth-child(n+57):nth-child(even):nth-child(-n+64) {
  background: #000;
}
<div id="chess">
    <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
    <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
    <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
    <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
    <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
    <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
    <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
    <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div>

Ответ 8

Готово. Пример: http://jsfiddle.net/LFVQU/1/

<style type="text/css">
    #chess{
     width:800px;   
     height:800px;
     border:1px;
     border:1px solid #999;
    }
    #chess div{
     width:100px;
     height:100px;  
     float:left;  
    }
#chess div{background: #fff}
#chess div:nth-child(1), #chess div:nth-child(3), #chess div:nth-child(5), #chess div:nth-child(7),
#chess div:nth-child(10), #chess div:nth-child(12), #chess div:nth-child(14), #chess div:nth-child(16),
#chess div:nth-child(17), #chess div:nth-child(19), #chess div:nth-child(21), #chess div:nth-child(23),
#chess div:nth-child(26), #chess div:nth-child(28), #chess div:nth-child(30), #chess div:nth-child(32),
#chess div:nth-child(33), #chess div:nth-child(35), #chess div:nth-child(37), #chess div:nth-child(39),
#chess div:nth-child(42), #chess div:nth-child(44), #chess div:nth-child(46), #chess div:nth-child(48),
#chess div:nth-child(49), #chess div:nth-child(51), #chess div:nth-child(53), #chess div:nth-child(55),
#chess div:nth-child(58), #chess div:nth-child(60), #chess div:nth-child(62), #chess div:nth-child(64)
{
    background-color:#000;
} 
</style>

Ответ 9

#chess {width:256px; height:256px; border:1px solid;}  
#chess div {width:32px; height:32px; display:inline-block; }
#chess div:nth-child(16n+1), #chess div:nth-child(16n+3),
#chess div:nth-child(16n+5), #chess div:nth-child(16n+7),
#chess div:nth-child(16n+10),#chess div:nth-child(16n+12),
#chess div:nth-child(16n+14),#chess div:nth-child(16n+16) {
  background-color:black;
}

Я думаю, что ответы с использованием float/clear лучше, только то, что я придумал.

Ответ 10

Для тех, кому нужна шахматная доска CSS3 с каждым квадратом с идентификатором, чтобы вы могли использовать его с JavaScript, я могу предложить это решение:

https://github.com/vpcom/CSS3-Chess-Board

Демо доступно здесь: http://vincentperrin.com/cr/css3/css3-chess-board/

Это делается с Sass (нотация SCSS), но вы также можете использовать обработанный файл CSS. Для тех, кто любит, подобные вещи также могут быть сделаны с Джейд.

Наслаждайтесь!

Ответ 11

Попробуйте следующее:

table.CHESS {
    border-collapse: collapse;
}

table.CHESS td {
    width: 50px;
    height: 50px;
    border: solid gray 1px;
}

table tr:nth-child(odd) td:nth-child(odd) {
    background: #000;
}

table tr:nth-child(even) td:nth-child(even) {
    background: #000;
}

Ответ 12

const HelloWorld = {
  template: '#tmpl',
  name: "HelloWorld",
  methods: {
    board (s) {
      return Array.from({length:s**2}).map((_,i)=>(parseInt(i/s,10)+1)%2===i%s%2)
    },
  },
};

new Vue({
  el: '#app',
  components: { HelloWorld },
  template: '<HelloWorld />'
})
.hello {
  display: grid;
  grid-template-columns: repeat(8, 20px);
}
.square {
  width: 20px;
  height: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<script type="text/x-template" id="tmpl">
  <div class="hello">
    <div
      class="square"
      v-for="(square, idx) in board(8)"
      :key="idx"
      :style="{ background: square ? '#FFF' : '#000' }"
    ></div>
  </div>
</script>

<div id="app"></div>

Ответ 13

Позвольте мне предложить вам более чистый CSS:

.divTableRow:nth-child(odd) .divTableCell:nth-child(even), .divTableRow:nth-child(even) .divTableCell:nth-child(odd) {
        background: #999;
    }

.divTableRow:nth-child(odd) .divTableCell:nth-child(even), .divTableRow:nth-child(even) .divTableCell:nth-child(odd) {
    background: #999;
}

.divTable {
    display: table;
    width: 60%;
    float: left;
}
.divTableRow {
    display: table-row;
}
.divTableHeading {
    background-color: #EEE;
    display: table-header-group;
}
.divTableCell, .divTableHead {
    display: table-cell;
    padding: 3px 10px;
    height: 12.5%;
    width: 12.5%;
    text-align: center;
}
.divTableHeading {
    background-color: #EEE;
    display: table-header-group;
    font-weight: bold;
}
.divTableFoot {
    background-color: #EEE;
    display: table-footer-group;
    font-weight: bold;
}
.divTableBody {
    background: white;
    display: table-row-group;
}
<div class="divTable">
   <div class="divTableBody">
      <div class="divTableRow">
         <div class="divTableCell">
            <div id="black-rock1" class="draggable black">♜</div>
         </div>
         <div class="divTableCell">
            <div id="black-knight1" class="draggable black">♞</div>
         </div>
         <div class="divTableCell">
            <div id="black-bishop1" class="draggable black">♝</div>
         </div>
         <div class="divTableCell">
            <div id="black-queen" class="draggable black">♛</div>
         </div>
         <div class="divTableCell">
            <div id="black-king" class="draggable black">♚</div>
         </div>
         <div class="divTableCell">
            <div id="black-bishop2" class="draggable black">♝</div>
         </div>
         <div class="divTableCell">
            <div id="black-knight2" class="draggable black">♞</div>
         </div>
         <div class="divTableCell">
            <div id="black-rack2" class="draggable black">♜</div>
         </div>
      </div>
      <div class="divTableRow">
         <div class="divTableCell">
            <div id="black-pawn1" class="draggable black">♟</div>
         </div>
         <div class="divTableCell">
            <div id="black-pawn2" class="draggable black">♟</div>
         </div>
         <div class="divTableCell">
            <div id="black-pawn3" class="draggable black">♟</div>
         </div>
         <div class="divTableCell">
            <div id="black-pawn4" class="draggable black">♟</div>
         </div>
         <div class="divTableCell">
            <div id="black-pawn5" class="draggable black">♟</div>
         </div>
         <div class="divTableCell">
            <div id="black-pawn6" class="draggable black">♟</div>
         </div>
         <div class="divTableCell">
            <div id="black-pawn7" class="draggable black">♟</div>
         </div>
         <div class="divTableCell">
            <div id="black-pawn8" class="draggable black">♟</div>
         </div>
      </div>
      <div class="divTableRow">
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
      </div>
      <div class="divTableRow">
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
      </div>
      <div class="divTableRow">
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
      </div>
      <div class="divTableRow">
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
         <div class="divTableCell">&nbsp;</div>
      </div>
      <div class="divTableRow">
         <div class="divTableCell">
            <div id="white-pawn1" class="draggable white">♙</div>
         </div>
         <div class="divTableCell">
            <div id="white-pawn2" class="draggable white">♙</div>
         </div>
         <div class="divTableCell">
            <div id="white-pawn3" class="draggable white">♙</div>
         </div>
         <div class="divTableCell">
            <div id="white-pawn4" class="draggable white">♙</div>
         </div>
         <div class="divTableCell">
            <div id="white-pawn5" class="draggable white">♙</div>
         </div>
         <div class="divTableCell">
            <div id="white-pawn6" class="draggable white">♙</div>
         </div>
         <div class="divTableCell">
            <div id="white-pawn7" class="draggable white">♙</div>
         </div>
         <div class="divTableCell">
            <div id="white-pawn8" class="draggable white">♙</div>
         </div>
      </div>
      <div class="divTableRow">
         <div class="divTableCell">
            <div id="white-rock1" class="draggable white">♖</div>
         </div>
         <div class="divTableCell">
            <div id="white-knight1" class="draggable white">♘</div>
         </div>
         <div class="divTableCell">
            <div id="white-bishop1" class="draggable white">♗</div>
         </div>
         <div class="divTableCell">
            <div id="white-queen" class="draggable white">♕</div>
         </div>
         <div class="divTableCell">
            <div id="white-king" class="draggable white">♔</div>
         </div>
         <div class="divTableCell">
            <div id="white-bishop2" class="draggable white">♗</div>
         </div>
         <div class="divTableCell">
            <div id="white-knight2" class="draggable white">♘</div>
         </div>
         <div class="divTableCell">
            <div id="white-rack2" class="draggable white">♖</div>
         </div>
      </div>
   </div>
</div>