Home > Net >  CSS: Text in a button is not centered
CSS: Text in a button is not centered

Time:07-16

My text in the button is not centered. I feel that this happens all the time. The text always seems to be a bit under the center. I tried to open the code with Chrome and Edge. They look the same. Here's a photo of the button

.button-container {
  display: flex;
  position: absolute;
  top: 10px;
  right: 10px;
  text-align: center;
  vertical-align: middle;
}

.button {
  color: white;
  font-family: arial;
  font-size: 28px;
  background-color: black;
  padding-left: 15px;
  padding-right: 15px;
  padding-top: 5px;
  padding-bottom: 5px;
  border-style: none;
  border-radius: 50%;
}
<div >
  <button >x</button>
</div>

CodePudding user response:

You are trying to position an element using hard coded padding values. My advice would be not to do that.

Remove the padding and change your x -> X. Then add these to your class

.button {height: 15px; aspect-ratio: 1/1;}

Whatever you set the height to the width will follow. With your border radius you can turn that clean box into a clean circle.

Edit: Recommendations aside, your main issue was caused by the use of a lowercase x which comes with a blank space 'baked in' above the letter. On the other hand, an uppercase X uses the whole line height and fills the container nicely.

CodePudding user response:

Removing everything but the following provided the desire result of centering:

.button-container {
  text-align: center;
  vertical-align: middle;
}

Padding, in the comment above, is appropriate as well. Take your padding and simply apply it to the .button-container CSS script. It will move the button down slight from the top as well, like so: enter image description here

CodePudding user response:

use for button class

.button {
   text-align: center;
}

CodePudding user response:

add below codes to class .button-container:

align-items: center;
justify-content: center;
  • Related