带有 CSS 网格的可点击图块

Clickable tiles with CSS Grid

我想为内容区域创建可点击的图块。为了实现这一点,我想使用 CSS 网格并使各个区域可点击。

<!DOCTYPE html>
<head>

<style class="cp-pen-styles">
body {
  margin: 40px;
}

.wrapper {
  display: grid;
  grid-template-columns: 100px 100px 100px;
  grid-gap: 10px;
  background-color: #fff;
  color: #444;
}

.box {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
}</style>
</head>
<body>
<div class="wrapper">
  <div class="box a">A</div>
  <div class="box b">B</div>
  <div class="box c">C</div>
  <div class="box d">D</div>
  <div class="box e">E</div>
  <div class="box f">F</div>
</div>

</body>
</html>

我知道我可以在单个单元格中放置 link,但也许可以单击整个单元格?

您可以使用javascript让单元格响应点击。或者,您可以将 a 标记用作网格,方法是将 display:block 添加到您的 .box 样式 class 并提供所需的任何其他 css 属性。

需要注意的是,您将无法在 a 标签内嵌套其他元素。

.box {
  display:block;
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
}</style>
</head>
<body>
<div class="wrapper">
  <a class="box a" href="some_link">A</a>
  <a class="box b" href="some_link">B</a>
  <a class="box c" href="some_link">C</a>
  <a class="box d" href="some_link">D</a>
  <a class="box e" href="some_link">E</a>
  <a class="box f" href="some_link">F</a>
</div>

一种不使用锚点的JS解决方案:

window.addEventListener("DOMContentLoaded", function() {
  let boxes = document.querySelectorAll(".box");

  Array.from(boxes, function(box) {
    box.addEventListener("click", function() {
      alert(this.classList[1]);
    });
  });
});
body {
  margin: 40px;
}

.wrapper {
  display: grid;
  grid-template-rows: 100px 100px;
  grid-template-columns: 100px 100px 100px;
  grid-gap: 10px;
  background-color: #fff;
  color: #444;
}

.box {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
/*   padding: 20px; */
  font-size: 150%;
  cursor: pointer;
  
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="wrapper">
  <div class="box a">A</div>
  <div class="box b">B</div>
  <div class="box c">C</div>
  <div class="box d">D</div>
  <div class="box e">E</div>
  <div class="box f">F</div>
</div>

现在您可以对每个单独的框使用 display: flex 来排列其内部内容。