英文:
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>
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 -->
<div class="box">
<a href="#">
<img src="http://placekitten.com/200/300" alt="img" >
</a>
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论