【问题标题】:Why is HTML button containing image so wide?为什么包含图像的 HTML 按钮如此宽?
【发布时间】:2021-08-07 09:48:21
【问题描述】:

我们 8 岁的儿子编写了以下 HTML 代码:

<button>
        <img src='https://i.stack.imgur.com/IEMUv.png' height=7% width=7% >
</button>

他很不高兴,因为按钮太宽了:

他想让我解释为什么按钮这么宽,但我不能。谁能帮我解释一下?

【问题讨论】:

  • 您不能使用具有heightwidth 属性的单位:developer.mozilla.org/en-US/docs/Web/HTML/Element/img
  • @JonP 好点。但是用style='height:7%;width:7%' 替换height=7% width=7% 会在按钮宽度方面产生相同的行为,所以这不是他抱怨的问题的原因

标签: html image button


【解决方案1】:

The percentage measurement is often considered as a percentage of the parent element

这就是事情变得有点循环的地方。按钮元素的宽度由图像的尺寸设置。然后,图像元素被设置为按钮而不是实际图像本身的百分比。

使用绝对单位 (px) 而不是 %

button img {
  height: 46px;
  width: 46px;
}
<button>
        <img src='https://i.stack.imgur.com/IEMUv.png' >
</button>

【讨论】:

    【解决方案2】:

    当您将图像的宽度设置为百分比时,button 会保留图像的原始宽度,并且仅图像会缩小7%

    您可以通过设置图像的绝对宽度来避免它。

    <button>
      <img src='https://i.stack.imgur.com/IEMUv.png' width="25">
    </button>

    【讨论】:

      猜你喜欢
      • 2017-09-19
      • 2014-12-21
      • 2014-03-12
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      • 2019-07-29
      • 2022-07-23
      • 2017-12-23
      相关资源
      最近更新 更多