CSS Grid布局中新增元素为何显示在网格图片后方
问题根源
.image__grid设置了position: absolute后会脱离正常文档流,不再占据页面排版空间,后续的元素会按照网格不存在的规则排布,直接被压在网格下层。你之前给后续元素加position: relative和z-index只是强行把元素层级抬到网格上方,并没有让元素回到网格下方的正常排版位置。另外你的代码里漏写了Grid布局必需的display: grid声明,配置的网格列、间距规则本身就没有生效。
修复步骤
- 移除
.image__grid的position: absolute属性,让网格容器回到正常文档流,自动占据对应高度,后续内容会自然排在它的下方 - 给
.image__grid补上display: grid声明,激活Grid布局,让你写的列宽、间距配置生效 - 删除
.attachment__title、.attachment__content上多余的position: relative、z-index属性,不需要手动调整层级,正常文档流下不会出现遮挡问题
修正后完整CSS代码
/*==================== Image Grid ====================*/ .grid__title { color: #ffcc00; text-shadow: 1px 1px #131313; margin: 10px; text-align: center; } .image__grid { display: grid; justify-content: center; align-items: center; margin: 10px auto; width: 100vw; grid-template-columns: repeat(auto-fill, minmax(300px, 300px)); column-gap: 10px; row-gap: 10px; } .image__grid img { width: 250px; height: 250px; object-position: center; } .attachment__title { color: #ffcc00; text-shadow: 1px 1px #131313; margin: 10px; text-align: center; } .attachment__content { margin: 10px; text-align: center; font-size: 24px; } .attachment__content a { text-decoration: none; font-weight: 700; font-size: 32px; }
修改后图片网格会正常渲染排版,下方的PDF板块会自动排列在网格底部,不会出现遮挡问题。
内容的提问来源于stack exchange,提问作者assem_hasan
相关产品推荐
相关产品推荐

