将一张图像放置在一个特定大小的 div 内的链接内。

huangapple go评论55阅读模式
英文:

Fit an image inside of a link inside of a div of a specific size

问题

如何将图像嵌入链接中的一个 div 中,而不使链接的大小变成 div 的大小?

例如,以下是一个视觉上看起来不错的解决方案(使用 Tailwind):

<div class="mb-12 h-[200px] w-[280px] bg-pink-500">
  <a href="#">
    <img src="http://placekitten.com/200/300" alt="img" class="h-full w-full object-contain" />
  </a>
</div>

但这会导致整个粉色背景可点击,而不仅仅是图像。我不希望发生这种情况,链接应该“贴合”图像。图像可以是任何大小,纵向或横向,而且我事先不知道大小,因此使用固定像素值将无法奏效。

英文:

How do you fit an image inside of a link inside of a div, without the link growing to the size of the div?

As an example, here's a solution (using Tailwind) that visually looks okay:

<div class="mb-12 h-[200px] w-[280px] bg-pink-500">
  <a href="#">
    <img src="http://placekitten.com/200/300" alt="img" class="h-full w-full object-contain" />
  </a>
</div>

将一张图像放置在一个特定大小的 div 内的链接内。

https://play.tailwindcss.com/BbZvEFCr6A

But this causes the entire pink background to be clickable instead of only the image. I don't want that to happen, the link should "hug" the image. The image can be any size, portrait or landscape, and I don't know the sizes beforehand, so using fixed pixels won't work.

答案1

得分: 2

不要为图像定义固定大小。请定义最大宽度/高度。

.box {
  max-width: 200px;
  max-height: 200px;
  background: pink;
  display: grid;
  place-content: center;
  
  /* 用于调试 */
  resize: both;
  overflow: hidden;
}

.box a {
  min-height: 0;
  min-width: 0;
}

.box a img {
  max-width: 100%;
  max-height: 100%;
}
<div class="box">
  <a href="#">
    <img src="http://placekitten.com/200/300" alt="img">
  </a>
</div>
英文:

Don't define fixed size for the image. Define max-width/height instead

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-css -->

.box {
  width: 200px;
  height: 200px;
  background: pink;
  display: grid;
  place-content: center;
  
  /* to debug */
  resize: both;
  overflow: hidden;
}

.box a {
  min-height: 0;
  min-width: 0;
}

.box a img {
  max-width: 100%;
  max-height: 100%;
}

<!-- language: lang-html -->

&lt;div class=&quot;box&quot;&gt;
  &lt;a href=&quot;#&quot;&gt;
    &lt;img src=&quot;http://placekitten.com/200/300&quot; alt=&quot;img&quot;  &gt;
  &lt;/a&gt;
&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月17日 18:19:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76703501.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定