原文連結: css 九宮格布局
上一篇: lz-string 面向localstorage的字元串壓縮庫
下一篇: 音頻播放錯誤的異常 [已解決]
之前做了幾個數字相關的小遊戲, 用到了類似的布局, 對于css這種東西, 還是用到再查吧
https://juejin.im/post/6886770985060532231#heading-7
不過這篇文章中也有幾個不錯的點
1, 使用 nth-child 來設定取消邊距, 比手寫class和寫死在css裡面好很多
2, 居中使用grid布局, 比flex少寫一行代碼
3, 顔色講到了 currentColor 這個确實沒怎麼了解
不過對于事件的綁定, 這個隻能說有時候還是要看情況, 不過确實在父級上綁定一個後, 直接用id來區分點選的是哪一個能減少一些開銷, 在這種簡單場景下使用完全沒問題, 但也不至于就怎麼滴了.....
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5COmNDOkJGO1U2NxIjYhBzNlZGMwYTOwMGM2IWO1IWZyEjMl1Cc19CX0VmbjN3bvwFdl5mLh5WaoN2cv5yZtl2Yz92Lc9CX6MHc0RHaiojIsJye.png)
仿照着實作了一下, 基本樣例就這樣了
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.wrap {
display: flex;
width: 300px;
flex-wrap: wrap;
}
.cell {
font-size: 40px;
display: grid;
place-items: center;
width: 100px;
height: 100px;
box-sizing: border-box;
border: 4px solid black;
background: deepskyblue;
color: white;
margin-left: -4px;
margin-top: -4px;
z-index: 1;
}
.cell:hover {
border: 4px red solid;
z-index: 2;
}
/* 第1、4、7個子元素 */
.cell:nth-child(3n + 1) {
/* 取消左負邊距 */
margin-left: 0;
}
/* 前三個子元素 */
.cell:nth-child(-n + 3) {
/* 取消上負邊距 */
margin-top: 0;
}
</style>
</head>
<div class="wrap" onclick="showItem(event)">
<div class="cell">1</div>
<div class="cell">2</div>
<div class="cell">3</div>
<div class="cell">4</div>
<div class="cell">5</div>
<div class="cell">6</div>
<div class="cell">7</div>
<div class="cell">8</div>
<div class="cell">9</div>
</div>
<body></body>
<script>
function showItem(e){
alert(e.target.innerText)
}
</script>
</html>