【问题标题】:background-image without background没有背景的背景图像
【发布时间】:2021-11-07 13:59:48
【问题描述】:

我正在使用带有background-image 属性集的按钮。我使用的图像是部分透明的,默认情况下它具有灰色背景。当我尝试使用background: transparent/white 时,我的图像突然不再缩放,尽管我使用了background-size: cover/contain

有没有办法在不使用<img> 内部按钮的情况下实现这一点?

或者有没有办法用 CSS 改变 HTML 属性? 因为我在java中伪造HTML,使用background-image的CSS类比每次都添加<img>更简单。

编辑:建议的答案:How to add background image for input type="button"? 不包括我的问题,虽然解决方案出现在 cmets 但出于不同的原因。所说的问题是关于向<input type="button"> 添加背景图像,这与我的<button> 不同,我首先添加图像没有问题(添加了我的图像),并且在提到的问题中,问题在于错字。

为了更清楚,我的代码是:

<button style="background-image: url('/path/to/my/image'); background-size: cover;">

它运行良好,但是 - 由于图像本身在某些地方是透明的 - 从下面可以看到灰色背景。当我将代码更改为:

<button style="background-image: url('/path/to/my/image'); background-size: cover; background: transparent;">

我摆脱了灰色背景,但我的图像不再缩小到按钮宽度。

将其更改为使用 background: url('/path/to/my/image'); 解决了问题。

【问题讨论】:

标签: html css


【解决方案1】:

您可以使用background 代替background-image

CSS 代码:

background: url('../image/button.png') no-repeat;

例子:

<html>
    <head>
        <style type="text/css">
            .btn{
                background: url(../image/button.png) no-repeat;
                cursor:pointer;
                border: none;
            }
        </style>
    </head>
    <body>
    <div id="submitForm">
        <input class="btn" type="button" name="button" value="Search"/>
     </div>          
    </body>
</html>

【讨论】:

  • 另一种可以尝试使用背景图像的方法:url(../image/button.png);
【解决方案2】:

你可以用type="imge"input标签来实现它

<input type="image" id="image" alt="Login"
       src="/media/examples/login-button.png">

MDN link

或者,您可以添加背景图像,如下所示:

.btn{
  width:200px;
  height: 50px;
  background-image: url(//unsplash.it/800);
  background-repeat: no-repeat;
  background-position: center;
  font-weight: 900;
  cursor:pointer;
  border: none;
  }
<form>
   <input class="btn" type="submit" value="Submit"/>
</form>

【讨论】:

  • 并非如此,因为我需要此按钮为“提交”类型以在点击时发送 POST 查询
  • @jbulatek 您可以设置 onClick 属性,然后从form 获取数据并发出POST 请求
猜你喜欢
  • 2016-08-04
  • 2022-07-21
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
  • 1970-01-01
  • 1970-01-01
  • 2012-01-01
  • 2012-03-01
相关资源
最近更新 更多