css实现按钮文案垂直水平居中,按钮左侧图标相对文字固定距离展示

需求

css实现按钮文案垂直水平居中,按钮左侧图标相对文字固定距离展示,效果如图:

 

实现

方案一:使用 margin-right 来实现按钮和左侧图标的间距

<div class="download-btn">
          <div class="btn-content" :class="{'left-icon': showLeftIcon}">
            <div class="left-icon">
            </div>
            <span class="btn-txt">点击查看</span>
          </div>
</div>
 .download-btn {
    width: 300px;
    height: 48px;
    background-color: #47a0ff;
    border-radius: 4px;
    font-size: 20px;
    margin-top: 30px;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 10px;
    .btn-content {
      width: auto;
      display: flex;
      align-items: center;
      justify-content: center;
      &.left-icon {
        margin-left: -36px;
      }
      .left-icon {
        width: 30px;
        height: 30px;
        margin-right: 6px;
      }
      .btn-txt {
        .line-clamp(1); // 限制按钮文字展示一行
        line-height: 1;
      }
    }
  }

实现逻辑,将按钮和图标放在同一个 div 里,按钮相对右侧文字,加一个 margin-right,按钮和图标的div 再整体向左移动左侧图标的宽度和左侧图标右间距,以保证按钮文字水平居中展示。

方案二:使用相对定位实现

<div class="download-btn">
            <div class="left-icon">
            </div>
            <span class="btn-txt"  :class="{'left-icon': showLeftIcon}">点击查看</span>
</div>
.download-btn {
    width: 300px;
    height: 48px;
    background-color: #47a0ff;
    border-radius: 4px;
    font-size: 20px;
    margin-top: 30px;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 10px;
    cursor: pointer;
    position: relative;
    .btn-content {
      width: auto;
      display: flex;
      align-items: center;
      justify-content: center;
      &.left-icon {
        margin-left: -36px;
      }
      .left-icon {
        width: 30px;
        height: 30px;
        position: relative;
        right: 10px;
      }
      .btn-txt {
        .line-clamp(1);
        line-height: 1;
        position: relative;
        text-align: center;
        &.left-icon{
          right: 10px;
       }
      }
    }
  }

实现逻辑,左侧图标相对右侧文字定位加间距,右侧文字右侧再加定位加间距,让文字水平居中。

posted @ 2024-05-29 11:41  蓓蕾心晴  阅读(20)  评论(0编辑  收藏  举报