【问题标题】:Center label of any size under a button in CSSCSS中按钮下任意大小的中心标签
【发布时间】:2022-12-29 00:11:16
【问题描述】:

我有一个按钮,标签绝对位于下方。

我希望标签不换行而是全部呈现在一行上。我知道我可以用 width: max-contentoverflow: visible 做到这一点。

但与此同时,我希望标签以按钮为中心,这是我无法找到的方法,除非我将标签换行。

我有什么办法可以做到这一点?

button {
    position: relative;
    width: 40px;
    height: 40px;
    background: #E30202;
    color: black;
    border-radius: 14px;
}

span {
  position: absolute;
  top: calc(45px);
  left: 0;
  font-size: 12px;
  color: black;
  width: 100%;
  pointer-events: none;
  /* width: max-content; */
}
<button>
  
  <span>Label Line</span>
</button>

【问题讨论】:

    标签: html css position


    【解决方案1】:

    所以你的文字居中。容器中的宽度不足以让文本仅落在一行上。您可以使用 psuedo-element :after 添加居中文本。但是您会注意到 sn-p 中的示例 1 似乎仍然没有居中。 buttonwidth 在第二个示例中翻了一番,使用相同的样式显示居中文本。

    另一种解决方案是添加 .wrapper 并将 display: flex;flex-flow: column;justify-content: center; 一起使用,以确保文本始终以按钮为中心。

    button {
      position: relative;
      width: 40px;
      height: 40px;
      background: #E30202;
      color: black;
      border-radius: 14px;
      margin: auto;
    }
    
    button.pseudo:after {
      content: "Label Line";
      position: relative;
      top: calc(100% + 3px);
    }
    
    .btn-wrapper:nth-child(2)>button {
      width: 80px;
    }
    
    .btn-wrapper {
      display: flex;
      flex-flow: column;
      justify-content: center;
      align-items: center;
      margin-top: 3em;
    }
    <!-- example 1 -->
    <div class="btn-wrapper">
      <button class="pseudo">
     
    </button>
    </div>
    
    <!-- example 2 -->
    <div class="btn-wrapper">
      <button class="pseudo">
     
    </button>
    </div>
    
    <!-- example 3 -->
    <div class="btn-wrapper">
      <button>btn</button>
      <span>Label Line</span>
    </div>

    【讨论】:

      猜你喜欢
      • 2012-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      • 2018-08-03
      • 2011-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多