Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't center a divs using CSS layouts

For some reason, Whenever I try to center a div using Flexbox using align-items and justify-content, It only centers the div horizontally. I can still center text though. Thanks in advance.

Here’s my code.

P.S. If it looks like the container is already vertically centered then try expanding the snippet.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@import url('https://fonts.googleapis.com/css2?family=Lato&family=Open+Sans&display=swap');
.outer-box {
  display:flex;
  justify-content:center;
  align-items:center;
}
.inner-box {
  background-color:#00c2fc;
  width:250px;
  height:130px;
  display:flex;
  justify-content:center;
  align-items:center;
  font-size: 35px;
  word-wrap: break-word;
  font-family:lato;
  font-weight:bold;
}

.box-text {
  text-align:center;
  padding:10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div class="outer-box">
    <div class="inner-box">
        <p class="box-text">
          I am not centered :(
        </p>
    </div>
  </div>

</body>
</html>

>Solution :

It is centered, but the height of the parent is being set by the content itself.

If you want it centered on the viewport you need to give the parent height of the viewport.

@import url('https://fonts.googleapis.com/css2?family=Lato&family=Open+Sans&display=swap');
.outer-box {
  display:flex;
  justify-content:center;
  align-items:center;
  height: 100vh;
}
.inner-box {
  background-color:#00c2fc;
  width:250px;
  height:130px;
  display:flex;
  justify-content:center;
  align-items:center;
  font-size: 35px;
  word-wrap: break-word;
  font-family:lato;
  font-weight:bold;
}

.box-text {
  text-align:center;
  padding:10px;
}

html, body { margin: 0; }
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div class="outer-box">
    <div class="inner-box">
        <p class="box-text">
          I amcentered :)
        </p>
    </div>
  </div>

</body>
</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading