'Self-taught: trying to center a textbox in the middle of the page by creating a div and using flex. It's currently centered at the top of the page
.align {
background: white;
display: flex;
align-items: center;
margin: 0 auto;
width: 60%;
}
<div class="align">
<p> This is filler text for a pretend blog </p>
</div>
Do I just add a bunch of padding to the top of the body? It does the trick but feels clunky and doesn't explain why flex isn't working.
Solution 1:[1]
The p element is at the vertical center of the .align element. This is not equal to being at the vertical center of the page. To make the p element be at the vertical center of the page, the .align element has to take up the whole height of the page. This could be done by applying height: 100vh to the .align element.
(If you want to horizontally center the p element, you have to apply justify-content: center to the .align element.)
(If the .align element is just for alignment, it could make sense to just remove it and simply apply
background: white;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
to the body:)
body {
background: white;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
<p>This is filler text for a pretend blog </p>
Solution 2:[2]
CSS Grid makes the process pretty painless.
/* remove default margin provided by browser user agent */
html {
margin: 0;
}
/* remove default top margin for exact vertical centering */
.align p {
margin-top: 0;
}
.align {
display: grid;
place-items: center;
min-height: 100vh;
}
<div class="align">
<p> This is filler text for a pretend blog </p>
</div>
Solution 3:[3]
.align {
background: white;
display: flex;
align-items: center;
justify-content: center;
width: 60%;
height: 50vh;
border: solid green 1px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
<div class="align">
<p> This is filler text for a pretend blog </p>
</div>
Solution 4:[4]
You need to set the height of the page and use justify-content: center; and align-items: center;
body {
background: white;
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100vh;
}
<div class="align">
<p> This is filler text for a pretend blog </p>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dtpnftscdsatp |
| Solution 2 | Andy Hoffman |
| Solution 3 | |
| Solution 4 |
