skip to Main Content

I’m making a website and I want to center a div horizontally and vertically, however, it won’t work.

Here’s the relevant HTML and CSS code for reference:

.loginWrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

.login {
  width: 300px;
  height: 300px;
  background-color: black;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login h1 {
    color: #FFF;
}
<div class="loginWrapper">
  <div class="login">
    <h1>lorem ipsum</h1>
  </div>
</div>

And here’s a
a photo of what’s happening on the website

3

Answers


  1. need to add this code overall div will be center in the body

      html, body {
      height: 100%;
      margin: 0;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    Login or Signup to reply.
  2. If you want login box over the content use positioning

    .loginWrapper {
      position: absolute;
      inset: 0;
      z-index: 2;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
    }
    
    .login {
      width: 300px;
      height: 300px;
      background-color: black;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .login h1 {
        color: #FFF;
    }
    <div class="loginWrapper">
      <div class="login">
        <h1>lorem ipsum</h1>
      </div>
    </div>
    Login or Signup to reply.
  3. Welcome to SO !

    Your div IS centered but the parent element is probably not taking the space you expect him too. Try adding some height: 100% / height: 100vh to the loginWrapper.

    If you still can’t center it, please provide the parent element code too, because in the provided snippet your div is perfectly centered

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search