css 创建具有背景色的网格

ca1c2owp  于 2023-08-08  发布在  其他
关注(0)|答案(5)|浏览(142)

我想创建一个19 * 19的网格。每个方格为50 px。在此网格中,奇数列的背景应为红色,偶数列的背景应为绿色。如何获得此信息?
这是我写的代码--下面链接了一个CodePen示例--有了这段代码,网格就像象棋一样,我不希望它是那样的。

body {
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: rgba(255, 255, 255, 0.5);
  font-family: Arial, sans-serif;
}

.colored-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  /*     grid-template-rows: repeat(193, 50px); */
  column-gap: 5px;
  height: auto;
  width: 100px;
  /* To accommodate 2 columns of 50px each */
}

.grid-cell {
  width: 50px;
  height: 50px;
  box-sizing: border-box;
}

.grid-cell:nth-child(odd) {
  background-color: red;
}

.grid-cell:nth-child(even) {
  background-color: green;
}

个字符
https://codepen.io/viy_bal/pen/GRwLBBr
这是我想要的输出,我编辑了这个问题-这些都是网格中的正方形,而不是网格间隙
enter image description here

ilmyapht

ilmyapht1#

为每一行添加一个 Package 器似乎是一种很好的方法。在这种情况下,网格的html应该看起来像这样:

<div class="colored-grid">
    <div class="wrapper">
      <div class='grid-cell'></div>
      <div class='grid-cell'></div>
      <div class='grid-cell'></div>
      <div class='grid-cell'></div>
      <div class='grid-cell'></div>
    </div>
    <div class="wrapper">
      <div class='grid-cell'></div>
      <div class='grid-cell'></div>
      <div class='grid-cell'></div>
      ...
    </div>
  </div>

字符串
display: contents添加到 Package 器的类中,剩下的代码将完成这项工作。
这是帮助我找到the solution的链接。
另外,here是我从你的代码编辑。

50pmv0ei

50pmv0ei2#

要创建19乘19的网格,您可以使用js创建单元格。

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>Colored Grid</title>
</head>

<body>
    <div class="colored-grid">
        <!-- The grid will be generated using JS -->
    </div>



    <script src="script.js"></script>

</body>

字符串

CSS

body {
    margin: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background-color: rgba(255, 255, 255, 0.5);
    font-family: Arial, sans-serif;
}

.colored-grid {
    display: grid;
    grid-template-columns: repeat(19, 50px);
    grid-template-rows: repeat(19, 50px);
    /* 19 columns of 50px each */
    gap: 5px;
    /* Gap between columns */
    height: auto;
    width: auto;
}

/* Apply red background to odd columns and green background to even columns */
.colored-grid>.even {
    background-color: red;
}

.colored-grid>.odd {
    background-color: green;
}

.grid-column {
    display: contents;
    /* To allow grid items to span entire column */
}

JS

document.addEventListener("DOMContentLoaded", function () {
  const coloredGrid = document.querySelector(".colored-grid");

  // Create a 19x19 grid
  for (let row = 0; row < 19; row++) {
    for (let col = 0; col < 19; col++) {
      const cell = document.createElement("div");
      cell.classList.add("grid-cell");

      // Apply red background to odd columns and green background to even columns
      if (col % 2 === 0) {
        cell.classList.add("even");
      } else {
        cell.classList.add("odd");
      }

      coloredGrid.appendChild(cell);
    }
  }
});

yb3bgrhw

yb3bgrhw3#

很高兴能帮到你!
我在codePen中看过你的代码,在css中只用偶数奇数是解决不了的,你需要的是给列着色,用nth-child(odd)/nth-child(even)你只会得到交错的网格,就像你说的- * 象棋 *。

解决方案:

下面是HTML:

<div class="colored-grid" id="GridContainer"></div>

字符串
首先,用JavaScript创建19 * 19的网格,循环时根据计算结果添加类名。

const TOTAL = 19 * 19
const GridContainer = document.getElementById('GridContainer')
for(let i = 0; i < TOTAL; i ++) {
  const GridCell = document.createElement('div')
  GridCell.className = 'grid-cell'  // adding a basic class name
  const colorClassName = (i % 19) % 2 ? 'green' : 'red'
  GridCell.classList.add(colorClassName)
  GridContainer.appendChild(GridCell)
}


CSS:

body {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.colored-grid {
  display: grid;
  grid-template-rows: repeat(19, 1fr);
  grid-template-columns: repeat(19, 1fr);
  gap: 6px;
}

.grid-cell {
  width: 50px;
  height: 50px;
}

.green { background-color: #2d802d; }
.red { background-color: #9e2121; }


在每一行中,奇数为红色,偶数为绿色,因此您可以简单地判断x % 2以确定其背景颜色。我们在每行中得到19个网格,所以如果我们想保持它们的规则相同,请设置另一个限制:

(i % 19)


这样我们就可以保持每一行都相同。effect
你可以在这里访问代码-> My Answer

23c0lvtd

23c0lvtd4#

一种方法-在代码中有解释性注解-如下;虽然我认为这应该是可能的,只有CSS,但我不能认为 * 如何 *,到目前为止。

// some simple utilities to reduce typing;
// caching a reference to the document:
let D = document,
  // an alias for document.createElement(), with the option to provide
  // properties for the created element:
  create = (tag, props) => Object.assign(D.createElement(tag), props),
  // an alias for both document.querySelector() - by default - and
  // Element.querySelector(), if an Element node is passed as the
  // context argument:
  get = (selector, context = D) => context.querySelector(selector),

  // caching a reference to the element in which the grid should
  // be appended:
  gridParent = get('.colored-grid[data-size]');

// defining a function to create the grid, taking one argument,
// the element in which the created elements are to be placed:
let createGrid = (source) => {

  // if there is no HTMLElement passed to the function we
  // return false and quit the function:
  if (!source || 1 !== source.nodeType) {
    return false;
  }

  // while the source element has any firstChild (this includes
  // text-nodes, comment nodes, and elements:
  while (source.firstChild) {
    // we use parentNode.removeChild to remove that firstChild;
    // had the childNodes been only elements, we could have
    // used HTMLElement.remove(), but that would (probably) have
    // left an accumulation of text-nodes behind in the DOM (which
    // I personally find messy, as inconsequential as it may be):
    source.removeChild(source.firstChild);
  }

  // using destructuring assignment to declare the variables
  // 'sz' and 'c', as aliases for 'size' and 'color' from
  // the source.dataset Object, as the variables need to
  // be modified for use in the function and I prefer to
  // use the 'meaningful' names once they're ready for use:
  let {
    size: sz,
    colors: c
  } = source.dataset,
    // here we create the 'size' variable, after using
    // parseInt() to convert the 'sz' string to a base-10
    // integer:
    size = parseInt(sz, 10),
    // and declare the 'colors' variable after creating an
    // array of colors from the supplied dataset-attribute;
    // first splitting the string on commas:
    colors = c.split(/,/)
    // using Array.prototype.filter() to retain
    // only those Array entries that:
    .filter(
      // both have an entry, have a non-zero length 
      // and which is not composed of just white-space:
      (color) => color && color.trim().length > 0
    )
    // we then use Array.prototype.map() to create a
    // new Array based on the filtered Array (which
    // retains or discards Array-elements, but doesn't
    // modify the Array elements):
    .map(
      // here we use String.prototype.trim() to
      // remove leading and trailing white-space:
      (color) => color.trim()
    ),
    // creating a document-fragment in order that all
    // created elements are appended to the document at
    // once, minimising reflows and repaints:
    fragment = D.createDocumentFragment();

  // to enable the size to be used in CSS, we use
  // CSSStyleDeclaration.setProperty() to set a '--size'
  // property, initialised to the value of the size integer:
  source.style.setProperty(`--size`, size);
  // we use Array.from() to create an Array from the provided
  // Object, which sets the length equal to the square of the
  // size integer (using Math.pow(<integer>,<power>) to do
  // so, but size * size would work equally well):
  Array.from({
      length: Math.pow(size, 2)
    })
    // iterating over the created Array, which passes in
    // a reference to the current Array-element (which is
    // undefined), and the index of the current Array-
    // element in the created Array:
    // within the Arrow function, we create a <div> element,
    // set its classList property using a template-literal,
    // to add the classes of 'grid-cell', 'row-n' (where n
    // is the row-number), 'row-odd' or 'row-even',
    // 'column-n' (where n is an integer, and reflects the
    // column-number), and column-odd or column-even:
    .forEach((_, i) => fragment.append(create('div', {
      classList: `grid-cell row-${ Math.floor(i/size) + 1}
                  row-${ 0 === Math.floor(i/size)%2 ? 'even' : 'odd'}
                  column-${ Math.floor(i%size) + 1}
                  column-${ 0 === Math.floor(i%size) + 1 ? 'odd' : 'even' }`,
      // we also set the --backgroundColor CSS custom property, which
      // cycles through the Array of colors passed via the data-colors
      // attribute:
      style: `--backgroundColor: ${ colors[(i%size)%colors.length] }`
      // the created element (on each iteration of the forEach()) is
      // appended to the document fragment using the initial fragment.append()
    })));

  // appending the fragment to the source, using Element.append():
  source.append(fragment);

};

// calling the function, passing in the gridParent element:
createGrid(gridParent);

// the below is largely irrelevant, it's just to enable some editing:
// here we use an Array literal along with spread syntax to create an
// Array of the child elements of the <fieldset> element; we then use
// Array.prototype.forEach() to iterate over those child-elements:
[...get('fieldset').children].forEach(
  // passing a reference to the current child element to the function:
  (child) => {
    // caching a reference to the <input> element within the
    // current child element:
    let input = get('input', child);

    // setting the value of the <input> to be equal to
    // the data-[input.name] attribute-value of the
    // gridParent element; so the value of the <input>
    // is equal to the current attribute-values on page-
    // load:
    input.value = gridParent.dataset[input.name];

    // binding the anonymous function as the event-handler
    // for the 'input' event:
    input.addEventListener('input', (evt) => {
      // using destructuring assignment to set
      // the variable 'target' to be equal to the
      // 'target' property-value of the Event (evt)
      // Object:
      let {
        target
      } = evt, {
        name,
        value
      } = target;

      // setting the gridParent's dataset[input.name]
      // attribute value to be equal to the value of the
      // <input>:
      gridParent.dataset[name] = value;
      createGrid(gridParent);
    });
  });
*,
::before,
::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  margin: 0;
  display: flex;
  flex-flow: column nowrap;
  gap: 1rem;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  /* using syntax from level 4 of the
     CSS Colors Module: */
  background-color: rgb(255 255 255 / 0.5);
  font-family: Arial, sans-serif;
}

form {
  backdrop-filter: blur(3px) brightness(300%) hue-rotate(25deg);
  background-color: #fff7;
  position: sticky;
  top: 0;
}

fieldset {
  display: flex;
  gap: 1rem;
  justify-content: space-between;
}

label {
  display: grid;
  gap: 0.5rem;
  padding: 0.5rem;
}

.colored-grid {
  counter-reset: cell;
  display: grid;
  gap: 5px;
  height: auto;
  grid-auto-rows: 50px;
  grid-template-columns: repeat(var(--size), 50px);
}

.grid-cell {
  background-color: var(--backgroundColor);
  counter-increment: cell;
}

/*
.grid-cell:nth-child(odd) {
  background-color: red;
}

.grid-cell:nth-child(even) {
  background-color: green;
}
*/

.even {
  background-color: red;
}

.odd {
  background-color: green;
}
<form action="#" method="post">
  <fieldset>
    <label>
      <span class="labelText">Number of grid-cells:</span>
      <input type="number" min="1" max="20" step="1" name="size"></label>
    <label>
      <span class="labelText">grid-column colours:</span>
      <input type="text" name="colors"></label>
  </fieldset>
</form>

<!--
  data-size: an integer, to define the number of cells on each axis,
  data-colors: a comma-separated list of colors to cycle through:
-->
<div class="colored-grid" data-size="10" data-colors="red, green"></div>

JS Fiddle demo的数据。

afdcj2ne

afdcj2ne5#

它可以使用css grid布局和:nth-child()选择器来实现。

.box {
  display: grid;
  height: 400px;
  width: 400px;
  gap: 10px;
  padding: 10px;
  grid-template-columns: repeat(3, auto);
}

.box > div {
  background-color: red;
}
.box > div:nth-child(2n) {
  background-color: green;
}

个字符
您可以添加更多的子divs,并更改grid-template-columns属性中的列数,在本例中为3。

相关问题