如何在CSS Grid单元格中居中显示cross.png 实现井字棋图片替换需求
问题根因
你遇到的问题核心是以下几个代码错误导致的:
- 原生CSS不支持嵌套写法,你将
.grid-container > div的样式规则写在了.grid-container的规则内部,导致单元格的flex居中样式完全不生效,图片无法被约束在单元格内。 - 未限制图片的尺寸,若原图尺寸大于100px的单元格大小,会撑破容器导致布局错位。
- 所有img元素默认是显示状态,不符合按需显隐的需求。
- HTML中每个img标签上多了多余的逗号,属于语法瑕疵。
修正后的CSS代码
.grid-container { display: inline-grid; grid-template-columns: 100px 100px 100px; grid-template-rows: 100px 100px 100px; border: 1px solid #000000; grid-gap: 1px; background-color: black; } /* 子元素规则移出父容器花括号才能生效 */ .grid-container>div { background-color: white; color: red; text-align: center; display: flex; justify-content: center; align-items: center; /* 防止图片溢出单元格 */ overflow: hidden; } /* 新增图片样式约束 */ .grid-container img { /* 限制图片最大尺寸,留边距避免贴边 */ max-width: 90%; max-height: 90%; /* 默认隐藏,需要时再通过JS修改为block显示 */ display: none; } #button1 { background-color: #4caf50; color: white; padding: 10px 16px; text-align: center; text-decoration: none; font-size: 16px; } #button2 { background-color: #614caf; color: white; padding: 10px 16px; text-align: center; text-decoration: none; font-size: 16px; } #button3 { background-color: #d36544; color: white; padding: 10px 16px; text-align: center; text-decoration: none; font-size: 16px; }
修正后的HTML代码
<div class="grid-container"> <div id="0"> <img id="img0" src="images/cross.png" alt="叉号"> </div> <div id="1"> <img id="img1" src="images/cross.png" alt="叉号"> </div> <div id="2"> <img id="img2" src="images/cross.png" alt="叉号"> </div> <div id="3"> <img id="img3" src="images/cross.png" alt="叉号"> </div> <div id="4"> <img id="img4" src="images/cross.png" alt="叉号"> </div> <div id="5"> <img id="img5" src="images/cross.png" alt="叉号"> </div> <div id="6"> <img id="img6" src="images/cross.png" alt="叉号"> </div> <div id="7"> <img id="img7" src="images/cross.png" alt="叉号"> </div> <div id="8"> <img id="img8" src="images/cross.png" alt="叉号"> </div> </div> <div class="choice-container"> <button id="button1">Cross</button> <button id="button2">Circle</button> <button id="button3">Reset</button> </div>
后续使用逻辑
后续你在JS中控制显隐时,只需要选中对应单元格的img元素,修改display属性为block即可显示,需要切换图案时修改src属性为images/circle.png即可。
内容的提问来源于stack exchange,提问作者Pi-R
相关产品推荐
相关产品推荐

