align center div with flex

Viewed 17

I`ve been struggling with some css code, specifycally with flex. First i had to figure it out how to stick footer at bottom but now i cant center my divs. Here is the html:

<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta
         name="viewport"
         content="width=device-width, initial-scale=1.0"
         />
      <link rel="stylesheet" href="style.css" />
   </head>
   <div class="page-container">
      <div class="content-wrap">
         <div class="optional-content-wrap">
            <h1>Write, edit and run HTML, CSS and JavaScript code online.</h1>
            <p>
               Our HTML editor updates the webview automatically in real-time as
               you write code.
            </p>
         </div>
      </div>
      <div>Footer</div>
   </div>
</html>
</div>

and the css:

.page-container {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.optional-content-wrap {
display: flex;
flex-direction: column;
align-items: center;
align-content: center;
}
.content-wrap {
flex: 1 1;
}
1 Answers

You want the children of the flex to be centered. So I set .content-wrap display to flex, and aligned items within. also text-align center.

.page-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}


.content-wrap {
  flex: 1 1;
}

.content-wrap {
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="style.css" />
</head>

<body>

  <div class="page-container">
    <div class="content-wrap">
      <div class="optional-content-wrap">
        <h1>Write, edit and run HTML, CSS and JavaScript code online.</h1>
        <p>
          Our HTML editor updates the webview automatically in real-time as you write code.
        </p>
      </div>
    </div>
    <div>Footer</div>
  </div>
</body>

</html>

Related