Vertical centering with Translate

Asked

Viewed 47 times

2

My dear, I have always used the tactic below to centralize my elements vertically that are contained in something with position Absolute, but for a while now it is no longer working, the element simply does not centralize but passes much of what would be the center.

I’m doing something wrong or this method no longer funf more?

position: relative
top: 50%;
transform: translateY(-50%);

I’m doing like this:

.content {
  position: relative;
  height: 100%;
  width: 100%;
}

.content .central {
  width: 60%;
  height: 100%;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 50%;
  transform: translateX(-50%);
}
<section class="content">

  <div class="central">

    <h1><b>Texto de teste</b></h1>

  </div>


</section>

  • 1

    Could make a [mcve] demonstrating the problem?

  • 1

    You can put the full html and css

  • I added the code to the question.

1 answer

1


Look what happens when you declare the translate 2x, the browser only recognizes the second, because it overwrites the first

inserir a descrição da imagem aqui

The right thing would be to use the long-hand thus:

transform: translateY(-50%) translateX(-50%);  

Or the short hand thus:

transform: translate(-50%, -50%);  

Where the first 50% is on the X-axis and the second 50% is the Y-axis

I put an edge just so you can see that the element is centered

inserir a descrição da imagem aqui

.content {
    position: relative;
    height: 100%;
    width: 100%;

}

.content .central {
    width: 60%;
    height: 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateY(-50%) translateX(-50%);
    border: 1px solid #000;
}
<section class="content">

    <div class="central">

        <h1><b>Texto de teste</b></h1>

    </div>

</section>

  • 1

    I understood the mistake I was making! Full answer, obg!

  • @Leonardohenrique without problems, keep in mind that this applies to other properties such as background. []s

Browser other questions tagged

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