Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering vertically and horzontally using translateX/Y not working as expected

Tags:

css

centering

This: vertical centering working 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 via

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

after uncommenting two lines in .container element in CSS I get weird result: the container is centered horizontally, but 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 via translateX/Y ?

like image 884
Dmitry Buzolin Avatar asked Sep 05 '14 01:09

Dmitry Buzolin


2 Answers

The reason it wasn't working was because the latter property would overwrite the previous one. Thus, you would 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 values like this:

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

or..

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

Updated Example - added vender prefixes.

like image 60
Josh Crozier Avatar answered Sep 28 '22 08:09

Josh Crozier


You're really close, change your CSS like this:

        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 fiddle here

like image 30
Devin Avatar answered Sep 28 '22 10:09

Devin