【问题标题】:Center image in button [duplicate]按钮中的中心图像[重复]
【发布时间】:2019-07-03 01:40:17
【问题描述】:

我正在尝试在按钮内添加一个图像,并希望将其居中对齐,因为我已将背景位置作为中心,但它仍然正确对齐。任何人都可以向我建议我应该如何将它对齐在中心?

demo.html

<html lang="en">
<head>
    <link rel="stylesheet" href="demo.css">
    <title>Document</title>
</head>
<body>
    <button class="closeIconRegion"> <span class="closeIconStyle"> </span></button>
</body>
</html>

demo.css

.closeIconRegion {
    position: relative; 
    overflow: hidden;
    width: 30px;
    height: 30px; 
    background: Orange; 
  } 

  .closeIconStyle {
    cursor: pointer;
    display: block;
    height: 25px !important;
    width: 25px !important;
    background-position: left;
    background-image: url(/images/closebtn_white.png);
    float: left;
  }

输出::

【问题讨论】:

    标签: html css


    【解决方案1】:

    如果您知道图像/按钮的高度和宽度,那么您可以在按钮本身中使用background-position: center,这将解决您的问题。

    .close-icon {
        width: 60px;
        height: 60px; 
        background: Orange; 
        background-image: url(https://via.placeholder.com/60);
        background-position: center;
      }
    &lt;button class="close-icon"&gt;&lt;/button&gt;

    如果您不知道图像/按钮的大小,那么我建议您使用flexbox 并在中心对齐。

    【讨论】:

      【解决方案2】:

      试试这个:

      .closeIconRegion {
          position: relative; 
          overflow: hidden;
          width: 30px;
          height: 30px; 
          background: Orange; 
          padding: 0;
          display: flex;
          align-items: center;
          justify-content: center;
        } 
      
      .closeIconStyle {
          cursor: pointer;
          display: block;
          height: 25px !important;
          width: 25px !important;
          background-position: center;
          background-image: url(/images/closebtn_white.png);
        }
      

      【讨论】:

        【解决方案3】:

        如果按钮的尺寸与图片的尺寸不一样,则应将background-size: cover设置为样式规则:

        button{
            background-image: url(https://placekitten.com/408/287);
            background-position: center;
            background-size: cover;
            height: 239px;
            width: 500px;
            
        }
        &lt;button&gt;&lt;/button&gt;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-09-24
          • 2021-12-28
          • 2018-04-07
          • 1970-01-01
          • 1970-01-01
          • 2012-07-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多