1/* Flex */
2.center {
3 display: flex;
4 justify-content: center;
5 align-items: center;
6}
7/* Without Flex */
8.parent {
9 position: relative;
10}
11.child {
12 position: absolute;
13 top: 50%;
14 transform: translateY(-50%);
15}
1/* No Flexbox */
2.parent {
3 position: relative;
4}
5.child {
6 position: absolute;
7 top: 50%;
8 transform: translateY(-50%);
9}
10
11/* With Flexbox */
12
13.parent {
14 display: flex;
15 flex-direction: column;
16 justify-content: center;
17}
18
19
20
1/*Remove comment to become a better programmer. */
2/* No Flexbox */
3.parent {
4 position: relative;
5}
6.child {
7 position: absolute;
8 top: 50%;
9 transform: translateY(-50%);
10}
11
12/* With Flexbox */
13
14.parent {
15 display: flex;
16 flex-direction: column;
17 justify-content: center;
18}
19
1/* 100vh = 100% Viewport Height */
2body {
3 display: flex;
4 height: 100vh;
5 flex-direction: column;
6 justify-content: center;
7}
8/* add */ align-items: center; /*to also center horizontally.*/
1<style>
2.container {
3 height: 200px;
4 position: relative;
5 border: 3px solid green;
6}
7
8.center {
9 margin: 0;
10 position: absolute;
11 top: 50%;
12 left: 50%;
13 -ms-transform: translate(-50%, -50%);
14 transform: translate(-50%, -50%);
15}
16</style>
17
18<div class="container">
19 <div class="center">
20 <p>I am vertically and horizontally centered.</p>
21 </div>
22</div>
1/* center vertically */
2/* No Flexbox */
3.parent {
4 position: relative;
5}
6.child {
7 position: absolute;
8 top: 50%;
9 transform: translateY(-50%);
10}
11
12
13
14/* With Flexbox */
15
16.parent {
17 display: flex;
18 flex-direction: column;
19 justify-content: center;
20}