How to center text vertically

Asked

Viewed 8,782 times

2

Can someone help me center the button texts? I’ve tried everything I found on the Internet and nothing works.

inserir a descrição da imagem aqui

  • Might help you "https://css-tricks.com/snippets/css/a-guide-to-flexbox/"

4 answers

4


You can use display: flex:

.button{
   width: 157px;
   height: 95px;
   background: yellow;
   text-align: center;
   float: left;
   top: 50%;
   position: relative;

   /* flex para alinhar conteúdo*/
   display: flex;
   justify-content: center;
   align-items: center;
}
<div>
   <a class="button">Texto do link teste 2 teste 2</a>
</div>

  • It worked, thank you very much!

1

You can do it that way too:

div {
  width: 100px;
  height: 100px;
  float: left;
  margin: 5px;
  display: table;
  background-color: #aaa;
}

div > a {
  text-align: center;
  display: table-cell;
  vertical-align: middle;
}
<div>
  <a href="#">Botão</a>
</div>

<div>
  <a href="#">Botão</a>
</div>

<div>
  <a href="#">Botão</a>
</div>

1

EDIT: Option with transform: translate the advantage of it is that vc will not depend on fixed values, because it will always align in the center of the box, regardless of its height and width.

.box {
    width: 200px;
    height: 100px;
    background-color: tomato;
    position: relative;
}
.box span {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
<div class="box">
    <span>Texto Item</span>
</div>


There are several options to center elements (horizontally and vertically). Without your code it is difficult to suggest the best option...

My suggestion, to be different from the others already answered, is to put the line-height with the same value as height box set

See the example below working:

.box {
    width: 200px;
    height: 100px;
    background-color: aquamarine;
    line-height: 100px;
    text-align: center;    
}
<div class="box">
    <span>Texto Item</span>
</div>

  • It gets centered with this code but the problem is that then it doesn’t present all the text that I have on the last button and it has to present all.

  • Melissa edited my answer, now look at the first example I gave in the answer, it uses transform: translate and will center whatever is inside regardless of the element size,

1

You can try to accomplish this way.

.flexbox-container {
   display: -ms-flexbox;
   display: -webkit-flex;
   display: flex;
   -ms-flex-align: center;
   -webkit-align-items: center;
   -webkit-box-align: center;
   align-items: center;
}

<div class="flexbox-container">
      <a href="#">Teste do botão</a>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.