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 ?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With