【问题标题】:CSS to scale img element's image to match containing button elementCSS 缩放 img 元素的图像以匹配包含按钮元素
【发布时间】:2020-12-27 21:39:14
【问题描述】:

有没有办法在 CSS 中缩放 img 元素的图像以匹配包含的按钮元素?

在此示例中,我希望图像以按钮为中心,并根据按钮的大小进行适当缩放。事实上,它们既没有适当缩放也没有对齐。

<html>
    <head>
        <title>Button img element scaling</title>
        <style type="text/css">
         div.container {
             display: flex;
             justify-content: center;
         }
         button {
             min-width: 20px;
             max-width: 20px;
             flex-basis: 20px;
             height: 20px;
         }
        </style>
    </head>
    <body>
        <div class="container">
            <button>
                <img src="https://fonts.gstatic.com/s/i/materialicons/clear/v6/24px.svg" />
            </button>
            <button>
                <img src="https://fonts.gstatic.com/s/i/materialicons/clear/v6/24px.svg" />
            </button>
        </div>
    </body>
</html>

我相信使用 div 代替按钮元素是可能的,但我问的是按钮元素(因为从语义上来说,让按钮成为按钮很好,而且我拥有的按钮已经设置了样式)。

我也相信有其他方法可以使用背景图像来解决这个问题,但由于这里的图像不仅仅是装饰,而且具有语义意义,我想使用一个 img(然后添加一个 alt 属性)。

该示例使用 flex,但问题似乎并非特定于此。

【问题讨论】:

    标签: html css


    【解决方案1】:

    我认为你可以在你的 css 中使用 object-fit -> https://www.w3schools.com/css/css3_object-fit.asp

    【讨论】:

    • 我确实试过了;它似乎适用于 div 元素,但不适用于按钮元素
    【解决方案2】:

    在按钮本身上显示 flex 似乎可以解决问题

    <html>
        <head>
            <title>Button img element scaling</title>
            <style type="text/css">
             div.container {
                 display: flex;
                 justify-content: center;
             }
             button {
                 min-width: 20px;
                 max-width: 20px;
                 flex-basis: 20px;
                 height: 20px;
                 display: flex;
                 align-items: center;
                 justify-content: center;
             }
            </style>
        </head>
        <body>
            <div class="container">
                <button>
                    <img src="https://fonts.gstatic.com/s/i/materialicons/clear/v6/24px.svg" />
                </button>
                <button>
                    <img src="https://fonts.gstatic.com/s/i/materialicons/clear/v6/24px.svg" />
                </button>
            </div>
        </body>
    </html>

    编辑

    如果它还需要增长到按钮大小,您可以在图像上添加width="100%" height="100%" 以使其缩放。

    看起来像这样:

    <img src="https://fonts.gstatic.com/s/i/materialicons/clear/v6/24px.svg" width="100%" height="100%" />
    

    【讨论】:

      猜你喜欢
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      • 2012-11-28
      • 1970-01-01
      相关资源
      最近更新 更多