遵循描述的技术 in this blog post我尝试制作一个 CSS 网格,其中我的图像将比居中的文本列更宽。但是,我无法让它工作,我不确定为什么。
我的 HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<main class="grid">
<div>
<p>Lorem ipsum [...]</p>
<p class="full"><a href="#"><img src="https://via.placeholder.com/500x250"></a></p>
<p>Lorem ipsum [...]</p>
</div>
</main>
</body>
</html>
还有CSS:
img {
width: 100%;
}
.grid {
display: grid;
grid-gap: 20px;
grid-auto-rows: 150px;
grid-template-columns:
[full-start] minmax(1em,1fr)
[main-start] minmax(0, 40em) [main-end]
minmax(1em,1fr) [full-end];
}
.grid > * {
grid-column: main ;
}
.full {
grid-column: full;
}
这在我的机器(Google Chrome、Windows)上呈现为此屏幕截图,其中图像未拉伸(stretch)到全宽:
我想首先实现此功能,因为我的目标是拥有一个三宽度布局:全宽、宽和文本(主)宽度:
| | | text width | | |
| | | text width | | |
| | | |
| | --- image width --- | |
| | | |
| | | text width | | |
| | | text width | | |
| |
| --------- full width --------- |
| |
| | | text width | | |
| | | text width | | |
首先,我希望可以实现全宽度/文本宽度,然后我将其扩展为第三个宽度(在上面的“图像宽度”中)。
我是否只是犯了一个我找不到的拼写错误,或者这个错误在其他地方?
最佳答案
网格属性影响网格项,它们是网格容器的直接子元素(这类似于 flex 盒)。这里,您在 main
网格容器内有一个额外的 div
包装器 - 删除它:
img {
width: 100%;
}
.grid {
display: grid;
grid-gap: 20px;
grid-auto-rows: 150px;
grid-template-columns: [full-start] minmax(1em, 1fr) [main-start] minmax(0, 40em) [main-end] minmax(1em, 1fr) [full-end];
}
.grid>* {
grid-column: main;
}
.full {
grid-column: full;
}
<main class="grid">
<!-- <div> -->
<p>Lorem ipsum [...]</p>
<p class="full">
<a href="#"><img src="https://via.placeholder.com/500x250"></a>
</p>
<p>Lorem ipsum [...]</p>
<!-- </div> -->
</main>
现在您的图像超出了其容器 - 您可以在图像上使用 object-fit
- 请参阅修改后的演示:
img {
width: 100%;
height: 100%; /* added */
object-fit: cover; /* added */
}
.grid {
display: grid;
grid-gap: 20px;
grid-auto-rows: 150px;
grid-template-columns: [full-start] minmax(1em, 1fr) [main-start] minmax(0, 40em) [main-end] minmax(1em, 1fr) [full-end];
}
.grid>* {
grid-column: main;
}
.full {
grid-column: full;
}
<main class="grid">
<!-- <div> -->
<p>Lorem ipsum [...]</p>
<p class="full">
<a href="#"><img src="https://via.placeholder.com/500x250"></a>
</p>
<p>Lorem ipsum [...]</p>
<!-- </div> -->
</main>
关于html - 使用 CSS 网格突破,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55851493/