首页 > 解决方案 > CSS 网格行具有不同的宽度

问题描述

我遇到了 CSS 网格的问题。我想知道我的每个网格行是否可以有不同的宽度。

我的网格设置如下:

.section.section--3 .text {
    display: grid;
    justify-content: center;
    padding: 0 10% 0;
    text-align: center;
}

所以我基本上希望嵌套在我的文本 div 中的标题、段落和按钮具有不同的宽度,而不使用 max-width 并且不填充整行。原因是我的按钮应该根据内部文本的长度动态调整宽度。

我的HTML如下:

<div class="text">
    <h2 class="text__item item--heading">
        Heading
    </h2>
    <p class="text__item item--paragraph">
        Paragraph
    </p>
    <a href="#" class="text__item item--button button button--primary">
        Button
    </a>
</div>

这张图片基本上说明了我想要实现的目标。

图像网格

谢谢。

标签: htmlcsscss-grid

解决方案


是的,这是可能的,而且有很多不同的方式。

让我展示一个:

.grid {
  
  display: grid;
  
  grid-template-columns: 20% 60%; /* Column width size here*/
  grid-template-rows: 100px 200px; /* Row height size here*/
  
  grid-column-gap: 10px;
  grid-row-gap: 10px;
}

.item.a{
  background-color: red;
}

.item.b{
  background-color: green;
}

.item.c{
  background-color: blue;
}

.item.d{
  background-color: yellow;
}
<div class="grid">
  <div class="item a"></div>
  <div class="item b"></div>
  <div class="item c"></div>
  <div class="item d"></div>
</div>

如果您真的喜欢 CSS 网格布局并想了解更多信息,我会在这里向您推荐这个网站。

希望能帮助到你, :)


推荐阅读