【问题标题】:Break out with css grid用 css 网格突围
【发布时间】:2019-09-15 00:23:42
【问题描述】:

按照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;
}

这会在我的机器(谷歌浏览器,Windows)上呈现到此屏幕截图,其中图像未拉伸到全宽:

我想先让这个工作,因为我的目标是有一个三宽度的布局:全宽、宽和文本(主)宽度:

|     |      | text width |      |      |
|     |      | text width |      |      |
|     |                          |      |
|     |  ---   image width  ---  |      |
|     |                          |      |
|     |      | text width |      |      |
|     |      | text width |      |      |
|                                       |
|  ---------   full width    ---------  |
|                                       |
|     |      | text width |      |      |
|     |      | text width |      |      |

一开始,我希望全宽/文本宽度是可能的,然后我会用第三个宽度(在“图像宽度”上方)扩展它。

我只是打错了我找不到的错字还是其他地方的错误?

【问题讨论】:

  • 您的 .full 图像不是网格的直接子元素,只有它的父 div 是网格项。确保图像在 div 之外(因此它是 main.grid 的直接子级)并且它的行为应该像您期望的那样。

标签: html css css-grid


【解决方案1】:

网格属性影响网格项,它们是网格容器的直接子元素(这类似于弹性框)。在这里,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>

【讨论】:

    猜你喜欢
    • 2012-09-01
    • 1970-01-01
    • 2020-03-31
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 2014-06-22
    相关资源
    最近更新 更多