嵌套CSS Grid内图片撑大容器,如何适配网格预设尺寸
解决方案
核心问题原因
- 外层Grid容器未显式定义行高规则,默认采用内容高度适配,大尺寸图片会直接撑开box1容器,挤压其他网格区域
object-fit属性错误添加到了#headerImage容器上,并未作用到实际的img元素上,适配规则未生效- 未给img元素添加宽高限制,图片保持原始尺寸渲染,撑大父级容器
- 原有代码存在语法疏漏:
grid-template-columns: repeat(1fr)、font: bold为无效写法,也会影响布局效果
修改代码
修改后的CSS代码
.grid { display: grid; grid-template-columns: 1fr 4fr 1fr; /* 显式定义行高,第一行(box1)100px,中间9行(box2-4)均分剩余高度,最后一行(box5)60px,可根据需求调整数值 */ grid-template-rows: 100px repeat(9, 1fr) 60px; background-color: #8b9dc3; height: 100vh; } .box1 { background-color: #3b5998; grid-column: 1/4; grid-row: 1/2; z-index: 2; padding: 1em; /* 限制box1最大高度为行高,避免内容溢出 */ max-height: 100%; overflow: hidden; } .box2 { grid-column: 1; grid-row-start: 2; grid-row-end: 12; color: white; } .box3 { background-color: #ffffff; grid-row: 2/12; grid-column: auto; color: black; } .box4 { align-self: stretch; grid-column: 3; grid-row: 2/12; color: white; } .box5 { background-color: #3b5998; grid-column: 1/4; } #headerImage { height: 100%; contain: content; } /* 新增图片适配规则 */ #headerImage img { width: 100%; height: 100%; object-fit: cover; } .nested { display: grid; /* 修正无效语法 */ grid-template-columns: 1fr; grid-auto-rows: 100%; grid-gap: 1px; } .nested > div { border: #333 1px solid; padding: 1em; } html, body { font-size: 14px; font-family: "Times New Roman", Times, serif; margin: 0; padding: 0; overflow: hidden; } .h1 { color: black; /* 修正无效语法 */ font-weight: bold; }
HTML代码无需调整,可直接复用原有代码
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="mystyle3.css"> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="grid"> <div class="box box1">box1 <div id="headerImage"><img src="https://wallpaperaccess.com/full/1713248.jpg" alt="a picture">BOX 1 </div> </div> <div class="box box2"> <div class="nested"> </div> </div> <div class="box box3">box3</div> <div class="box box4">box4</div> <div class="box box5">box5</div> </div> </body> </html>
内容的提问来源于stack exchange,提问作者Undead Space
相关产品推荐
相关产品推荐

