前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >css实现按钮文案垂直水平居中,按钮左侧图标相对文字固定距离展示

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

作者头像
蓓蕾心晴
发布2024-05-30 12:46:36
1260
发布2024-05-30 12:46:36
举报
文章被收录于专栏:前端小叙前端小叙

需求

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

实现

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

代码语言:javascript
复制
<div class="download-btn">
          <div class="btn-content" :class="{'left-icon': showLeftIcon}">
            <div class="left-icon">
            </div>
            <span class="btn-txt">点击查看</span>
          </div>
</div>
代码语言:javascript
复制
 .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 再整体向左移动左侧图标的宽度和左侧图标右间距,以保证按钮文字水平居中展示。

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

代码语言:javascript
复制
<div class="download-btn">
            <div class="left-icon">
            </div>
            <span class="btn-txt"  :class="{'left-icon': showLeftIcon}">点击查看</span>
</div>
代码语言:javascript
复制
.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;
       }
      }
    }
  }

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-05-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 需求
  • 实现
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档