首页 > 解决方案 > 在 CSS 中显示来自十个图标的图像中的单个图标,它们也必须缩放?

问题描述

在 CSS 中,如果我有一个包含十个 100x100 像素的图标的单个文件。它是icons.png

我想要我的 html 中的图像

<img alt="The third image in the file, but scaled to 30x30"> &nbsp; Menu

但是,我想要文件中的第三个图像(位置 [200,0] 和宽度 100x100) ,但是将完整的 100x100 图标缩放到 30x30 像素。

这可以在没有任何 JavaScript 的 CSS/HTML 中完成吗?

标签: htmlcssimagescale

解决方案


您可以使用 :nth-child() 选择器来选择父 div 的第三个孩子。

HTML

<div>
  <img src="https://via.placeholder.com/100x100"> &nbsp; Menu
  <img src="https://via.placeholder.com/100x100"> &nbsp; Menu 
  <img src="https://via.placeholder.com/100x100"> &nbsp; Menu 
  <img src="https://via.placeholder.com/100x100"> &nbsp; Menu 
  <img src="https://via.placeholder.com/100x100"> &nbsp; Menu
  <img src="https://via.placeholder.com/100x100"> &nbsp; Menu
  <img src="https://via.placeholder.com/100x100"> &nbsp; Menu
  <img src="https://via.placeholder.com/100x100"> &nbsp; Menu
  <img src="https://via.placeholder.com/100x100"> &nbsp; Menu
  <img src="https://via.placeholder.com/100x100"> &nbsp; Menu
</div>

CSS

div img {
  width: 100px;
  height: 100px;
}
div img:nth-child(3) {
  width: 30px;
  height: 30px;
}

工作演示


推荐阅读