Well, I can't vertically center a content using CSS Grid, with Flexbox I had no problems, I'm just starting with CSS Grid. This is what I have tried:
Use the classic method with transform
and translateY
:
.body {
height: 100%;
}
.grid {
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
I also tried using a container that wraps the grid like so:
.container {
align-items: center;
justify-content: center;
height: 100%;
}
But none of this has worked for me.
What I want is to center the div
with class .grid
relative to the height of the device where the page loads (that's why I added the 100vh
to body
).
I share my code:
* {
box-sizing: border-box;
}
body {
color: white;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
align-items: center;
margin: 2rem!important;
}
.grid {
display: grid;
grid-gap: 2rem;
grid-template-columns: [inicio-contenido] 1fr [fin-contenido];
grid-template-rows: auto [inicio-contenido] auto [fin-contenido];
}
@media (min-width: 640px) {
.grid {
grid-template-columns: 4fr [inicio-contenido] 4fr [fin-contenido];
}
header {
grid-column: 1 / 3;
}
aside {
grid-column: 1;
grid-row: 2;
}
footer {
grid-column: 1 / 3;
grid-row: 3;
}
}
article {
grid-column: inicio-contenido;
grid-row: inicio-contenido;
}
header,
aside,
article,
footer {
background: #333;
padding: 2rem;
border-radius: .4rem;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<body>
<div class="grid">
<header>Header</header>
<aside>Aside</aside>
<article>
<h1>Mi título</h1>
<p>Contenido cool</p>
</article>
<footer>Footer</footer>
</div>
</body>
PS: For some reason, here in the snippet it is taking my styles first
normalize.css
and not mine, I had to add the!important
body for this reason.
I attach an image of what I want to achieve: Side A is what I currently have, side B is how I want it to be, centered depending on the height of the browser.
Considers:
You can build it this way.
Process
div
the with the class , that is, apply agrid
label , so that in this way its child node, which is the one with the class , becomes flexible and we can move it on one of the axes that make up the flexboxbody
display: flex;
div
grid
Example
Note: Try this code in some system like JS Fiddle so you can better see how it works
I add the snnipet with the example
Try putting vertical centering on the particular container tag via CSS: