首页 > 解决方案 > 根据按钮位置动态标注位置

问题描述

我正在开发一个界面,该界面允许用户更改按钮位置并在按钮下编写标签文本。我的问题是,标签并不总是在按钮下方居中,这取决于文本标签的大小和字母数量,

这是我的 CSS 课程

    .button-wrapper {
    display: inline-block;
    max-width: 80px;
    text-align: center;}


    .button-wrapper > button {
    display: block;
    height: 75px;
    width: 75px;
    border-radius: 50%;
    position: relative;
    border: 1px solid gray;
    text-align: center;
    :active  {border: 3px solid yellow;}
    :hover{border: 2px solid red;}}

    .button-wrapper > label {
    display: block;
    position: relative;
    font-size: 14px;
    margin:0 auto; left:0; right:0;
    padding: 3px;}

这是我的 html 代码

     <div class="button-wrapper">
        <button
                [class.btn-primary]="true"
                [style.color]="buttonStyle.labeLFontColor"
                [ngStyle]="{'margin-left': bar.accessPosition+'%','font-style': buttonStyle.labeLFontFamily, 'font-size.px':buttonStyle.labeLFontSize, 'font-weight':buttonStyle.labeLFontWeight,
                'background-color': buttonStyle.backgroundColor, 'font-family': buttonStyle.labeLFontFamily, 'border-color': buttonStyle.borderColor,
                     'border': buttonStyle.borderSize+'px solid', 'background':'url(assets/showcase/images/accessButtons/' + bar.accessBackImage+') white center center no-repeat',
                 'background-size': '100% 75px'}">
        </button>
        <label  *ngIf="useLabel"  [ngStyle]="{'margin-left': bar.accessPosition+'%','font-style': buttonStyle.labeLFontFamily, 'font-size.px':buttonStyle.labeLFontSize, 'font-weight':buttonStyle.labeLFontWeight,'font-family': buttonStyle.labeLFontFamily }">{{accessLabel}}</label>
    </div>

如您所见,标签大小是动态的,标签文本也有输入来编写文本...那么如何将标签固定为始终居中并低于用户所写的任何内容。谢谢你。

标签: htmlcssangulardynamiclabel

解决方案


根据您提供的stacblitz 链接,以下 CSS 可能是您想要实现的(只需将您的 CSS 替换为此):

.button-wrapper {
  display: grid;
  justify-items: center;
}

.button-wrapper > button {
  display: block;
  height: 75px;
  width: 75px;
  border-radius: 50%;
  position: relative;
  border: 1px solid gray;
}

.button-wrapper > button:hover {
  border: 2px solid red;
}

.button-wrapper > button:focus {
  border: 3px solid yellow;
}

.button-wrapper > label {
  border: 1px solid red;
  display: block;
  position: relative;
  font-size: 14px;
  margin: 0 auto;
  left: 0;
  right: 0;
  padding: 3px;
}

笔记:

  • 你的一些 CSS 结构很糟糕
  • 对于任何布局和定位,请考虑CSS Grid

推荐阅读