如何用HTML元素完全填充CSS网格盒?

发布于 2025-02-06 02:26:03 字数 1234 浏览 1 评论 0原文

- 在下面进行编辑 -

我希望在如何填充HTML元素的CSS网格盒上寻求您的帮助。

创建CSS网格并将HTML元素分配给某些行和列之间的位置,如果我们希望该元素在这些行和列之间占据整个空间,我们是否需要直接更改元素维度?还是还有另一种方式?

例如,如果我们有一个IMG元素并将其分配到CSS网格位置,则可以将IMG的宽度和高度属性设置为100%,并且IMG将在这些网格行和列之间填充。我希望问是否有另一种方法可以用IMG填充该空间,而无需直接更改IMG元素的尺寸?还是,至少不使用高度和宽度特性?

- 编辑 -

非常感谢您抽出宝贵的时间让我知道!我在HTML和CSS的下面包括了一个最小可再现的示例。

HTML

<!DOCTYPE html>
<html lang="en">

<head>
  <link href="site.css" rel="stylesheet">
</head>

<body>
  <div id="grid-container">
    <div id="stretch-text">Stretch</div>
    <div id="unstretched-text">Unstretched</div>
    <img id="stretch-img" src="example.jpg">  
  </div>
</body>

</html>

CSS

#grid-container {
    display: grid;
    grid-template-rows: 300px 300px;
    grid-template-columns: 300px 300px;
}

#stretch-text {
    grid-column-start: 1;
    grid-column-end: 3;
    grid-row-start: 2;
}

#unstretched-text {
    grid-column-start: 2;
    grid-column-end: 2;
    grid-row-start: 2;
}

#stretch-img {
    grid-column-start: 1;
    grid-column-end: 3;
    grid-row-start: 1;
    /* width: 100%;
    height: 100%; */
}

-- Edits Below --

I’m hoping to ask for your help on how to fill a CSS Grid box with an html element.

Once we create a CSS Grid and assign an html element to a location between some rows and columns, if we want the element to take up the full space between these rows and columns, do we need to change the element dimensions directly? Or is there another way?

For example, if we have an img element and assign it to a CSS Grid location, we can set the width and height properties of the img to 100% and the img will fill between those grid rows and columns. I’m hoping to ask if there’s another way to fill that space with the img without changing the img element’s dimensions directly? Or, at least without using the height and width properties?

-- Edits --

Thank you so much for taking the time to let me know ! I've included a minimally reproducible example below of HTML and CSS.

HTML

<!DOCTYPE html>
<html lang="en">

<head>
  <link href="site.css" rel="stylesheet">
</head>

<body>
  <div id="grid-container">
    <div id="stretch-text">Stretch</div>
    <div id="unstretched-text">Unstretched</div>
    <img id="stretch-img" src="example.jpg">  
  </div>
</body>

</html>

CSS

#grid-container {
    display: grid;
    grid-template-rows: 300px 300px;
    grid-template-columns: 300px 300px;
}

#stretch-text {
    grid-column-start: 1;
    grid-column-end: 3;
    grid-row-start: 2;
}

#unstretched-text {
    grid-column-start: 2;
    grid-column-end: 2;
    grid-row-start: 2;
}

#stretch-img {
    grid-column-start: 1;
    grid-column-end: 3;
    grid-row-start: 1;
    /* width: 100%;
    height: 100%; */
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文