Centering vertically and horizontally with translateX / Y does not work properly

This: vertical centering works great Code:

` <div class="container"> <h1>Vertical center with only 3 lines of code</h1> <section class="text"> <p>I'm vertically aligned! Hi ho Silver, away!</p> </section> </div>` 

However, if I try to center horizontally using the same approach, using

 left: 50%; translateX(-50%); 

after splitting two lines in the .container element in CSS I get a strange result: the container is centered horizontally, but the vertical centering is lost. What am I missing here and how to achieve what I want: to center the container vertically and horizontally on the page using translateX / Y?

+6
source share
2 answers

The reason it didn't work was because the last property would overwrite the previous one. Thus, you will only see horizontal centering.

 .container { position: absolute; top: 50%; left: 50%; transform: translateY(-50%); /* This would be overwritten */ transform: translateX(-50%); /* By this.. */ } 

The solution would be to combine the following values:

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

or..

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

Updated example - vender prefixes added.

+9
source

You are really close, change your CSS as follows:

  body { font-family: Helvetica Neue, Helvetica, sans-serif; background: #59488b; padding: 1em; text-align:center; } * { text-align:center; } .container { position: absolute; top: 50%; left:50%; transform: translateY(-50%) translateX(-50%); border: 2px solid red; } .text p { position: relative; top: 50%; transform: translateY(-50%); } section { display: block; max-width: 500px; background: #433669; margin: 0 auto 1em; height: 100px; border-radius: .5em; color: white; padding: 1em; } 

See the fiddle here

+1
source

Source: https://habr.com/ru/post/974862/


All Articles