Search code examples
htmlcssposition

Center label of any size under a button in CSS


I've got a button with a label absolutely positioned underneath.

I want the label to not wrap to a new line but to be rendered all on one line. I know i can do that with width: max-content or with overflow: visible.

But at the same time i want the label to be centered with the button, which is what i can't find a way to do unless i wrap the label to a new line.

Any way i can achieve this? enter image description here

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>


Solution

  • So your text is centered. There is just not enough width in the container for the text to fall on only one line. You can use the psuedo-element :after to add the centered text. But you'll notice the example 1 in the snippet still doesn't seem centered. The width of the button is doubled on the second example with the same styles showing the centered text.

    Another solution would be to add a .wrapper and use display: flex; with flex-flow: column; and justify-content: center; to make sure the text is always centered with the button.

    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>