使用普通的<img>标签可以使用CSS背景图像和背景位置以相同的方式偏移图像吗?
页面上有主要图像,当两者都被加载(因此增加带宽)时,单独的缩略图是没有意义的.有些图像是纵向的,有些是横向的,但是我需要以均匀的尺寸显示缩略图(并在不符合所需宽高比的情况下裁掉多余的图像).
虽然使用其他标签和background-CSS值可以实现,但使用普通的<img>标签会更好.
Pat*_*Pat 19
不幸的是,只有一个<img>标签是不可能的.我可以为您的问题考虑两种解决方案:
CSS背景图像
创建<div>将图像应用为背景图像属性的位置:
<div class="thumbnail" style="background: url(an-image.jpg) no-repeat 50% 50%"></div>
Run Code Online (Sandbox Code Playgroud)
CSS剪辑
使用该clip-path属性仅显示图像的一部分:
<!-- Clip properties are top, right, bottom, left and define a rectangle by its top-left and bottom-right points -->
<div style="clip-path: inset(10px 200px 200px 10px)">
<img src="an-image.jpg">
</div>
Run Code Online (Sandbox Code Playgroud)
您可以在本文中阅读更多相关信息.
mar*_*tin 10
这是一个老问题,但这是我在谷歌搜索这个问题时出现的第一个问题,所以我想我会提到这个答案,在我看来,这个答案实际上解决了如何模拟background-position属性的原始问题。我找到的答案是使用 CSS 属性object-position和object-fit. 例如这样:
<img src="logos.png" style="object-fit: none; object-position: -64px 0; width: 32px; height: 32px" />
Run Code Online (Sandbox Code Playgroud)
这将显示第一行中的第三个缩略图(假设缩略图排列在 32 x 32 像素的规则网格中)。
小智 8
如果将图像放在div中,则可以使用边距移动图像.此特定示例使用精灵图像徽标作为主页链接,在悬停时更改位置.您也可以跳过A标签并使用#logo img上的margin属性移动图像.
HTML:
<div id="logo">
<a href="#">
<img src="img/src.jpg" />
</a>
</div>
Run Code Online (Sandbox Code Playgroud)
CSS:
#logo {
display: block;
float: left;
margin: 15px 0;
padding: 0;
width: 350px; //portion of the image you wish to display
height: 50px; //portion of the image you wish to display
overflow: hidden; //hide the rest of the image
}
#logo img {
width: 350px;
height: 100px; // you'll see this is 2x the height of the viewed image
padding: 0;
margin: 0;
}
#logo a {
display: block;
float: left;
margin: 0;
padding: 0;
}
#logo a:hover {
margin-top: -50px; //move up to show the over portion of the image
}
Run Code Online (Sandbox Code Playgroud)
希望有所帮助!