Clickable tiles with CSS Grid

11.3k views Asked by At

I want to create clickable tiles for a content area. To realize this I wanted to use CSS Grid and make the individual areas clickable.

<!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>

I understand that I could put a link in the individual cells, but maybe it is possible to click the single cell as a whole ?

2

There are 2 answers

2
Kostas Siabanis On BEST ANSWER

A JS solution that uses no anchors:

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>

Now you can use display: flex to each individual box to arrange it's inner content.

2
Julio Feferman On

You can use javascript to make the cells respond onclick. Alternatively, you can use the a tag behave as a grid, by adding display:block to your .box style class and provide any other css attributes needed.

The caveat is that you won't be able to nest other elements inside your a tags.

.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>