原文链接: css 九宫格布局
上一篇: lz-string 面向localstorage的字符串压缩库
下一篇: 音频播放错误的异常 [已解决]
之前做了几个数字相关的小游戏, 用到了类似的布局, 对于css这种东西, 还是用到再查吧
https://juejin.im/post/6886770985060532231#heading-7
不过这篇文章中也有几个不错的点
1, 使用 nth-child 来设置取消边距, 比手写class和写死在css里面好很多
2, 居中使用grid布局, 比flex少写一行代码
3, 颜色讲到了 currentColor 这个确实没怎么了解
不过对于事件的绑定, 这个只能说有时候还是要看情况, 不过确实在父级上绑定一个后, 直接用id来区分点击的是哪一个能减少一些开销, 在这种简单场景下使用完全没问题, 但也不至于就怎么滴了.....
仿照着实现了一下, 基本样例就这样了
<!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>