首页 > 解决方案 > 使用 css grid minmax 和 a href 属性

问题描述

我是使用 CSS 网格的新手。我正在尝试制作大小不同的图像响应网格。我想出的例子很完美,但似乎我需要定义一个大小repeat(auto-fit, minmax(84px, max-content));而不是像repeat(auto-fit, minmax(min-content, max-content));我使用auto-fit. a href即使图像本身不是 84 像素,这也会使属性扩展 84 像素。

有没有一种方法可以使用auto-fit,同时让行和列像现在一样完美契合,而不必将大小定义为 84px?或者有没有更好的方法来做到这一点,同时保持简单?

a {
  border: 2px dashed pink;
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(84px, max-content));
  align-items: center;
  grid-gap: 2rem;
}

.ef {
  background: url(https://fakeimg.pl/84x84/) no-repeat 0px 0px;
  width: 84px;
  height: 84px;
}

.eft {
  background: url(https://fakeimg.pl/16x16/) no-repeat 0px 0px;
  width: 16px;
  height: 16px;
}

.ytt {
  background: url(https://fakeimg.pl/44x44/) no-repeat 0px 0px;
  width: 44px;
  height: 44px;
}
<p>
  The grid is fine but the a href extends too far for some reason.
</p>

<section class="grid">
  <a href="/ytt">
    <div class="ytt"></div>
  </a>

  <a href="/ef">
    <div class="ef"></div>
  </a>

  <a href="/ef">
    <div class="ytt"></div>
  </a>

  <a href="/ef">
    <div class="ytt"></div>
  </a>

  <a href="/ef">
    <div class="ef"></div>
  </a>

  <a href="/ef">
    <div class="eft"></div>
  </a>

  <a href="/ef">
    <div class="eft"></div>
  </a>

  <a href="/ef">
    <div class="ef"></div>
  </a>

 <a href="/ef">
    <div class="eft"></div>
  </a>

  <a href="/ef">
    <div class="ytt"></div>
  </a>
  
  <a href="/ef">
    <div class="ytt"></div>
  </a>

  <a href="/ef">
    <div class="ytt"></div>
  </a>
</section>

标签: htmlcsscss-grid

解决方案


简单地改变justify-items。默认情况下,项目将被拉伸以填充网格区域,因为默认对齐方式是拉伸。您已经使用 . 在横轴上更改了它align-items。我们使用 . 对主轴做同样的事情justify-items。您会注意到这两个属性都接受拉伸作为值

a {
  border: 2px dashed pink;
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(84px, max-content));
  align-items: center;
  justify-items:center;
  grid-gap: 2rem;
}

.ef {
  background: url(https://fakeimg.pl/84x84/) no-repeat 0px 0px;
  width: 84px;
  height: 84px;
}

.eft {
  background: url(https://fakeimg.pl/16x16/) no-repeat 0px 0px;
  width: 16px;
  height: 16px;
}

.ytt {
  background: url(https://fakeimg.pl/44x44/) no-repeat 0px 0px;
  width: 44px;
  height: 44px;
}
<p>
  The grid is fine but the a href extends too far for some reason.
</p>

<section class="grid">
  <a href="/ytt">
    <div class="ytt"></div>
  </a>

  <a href="/ef">
    <div class="ef"></div>
  </a>

  <a href="/ef">
    <div class="ytt"></div>
  </a>

  <a href="/ef">
    <div class="ytt"></div>
  </a>

  <a href="/ef">
    <div class="ef"></div>
  </a>

  <a href="/ef">
    <div class="eft"></div>
  </a>

  <a href="/ef">
    <div class="eft"></div>
  </a>

  <a href="/ef">
    <div class="ef"></div>
  </a>

 <a href="/ef">
    <div class="eft"></div>
  </a>

  <a href="/ef">
    <div class="ytt"></div>
  </a>
  
  <a href="/ef">
    <div class="ytt"></div>
  </a>

  <a href="/ef">
    <div class="ytt"></div>
  </a>
</section>


推荐阅读