skip to Main Content

So I’ve tried centering a div, but only the children get effected.

What am I doing wrong?

Here’s my current code:

<div class="card">
  <img src="images/image-equilibrium.jpg" alt="Image">
</div>

And my CSS:

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

Here’s what’s actually happening:

Image example 1

2

Answers


  1. Use the flexbox on the parent, not on the div you want to center:

    .parent {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .card {
      width: 200px;
      height: 200px;
      background-color: black;
    }
    <div class="parent">
      <div class="card">
        <img src="images/image-equilibrium.jpg" alt="">
      </div>
    </div>

    If you want to keep the HTML structure (not inserting parent), you could just use the horizontal margin auto like this:

    .card {
      width: 200px;
      height: 200px;
      background-color: black;
      margin: 0 auto;
    }
    <div class="card">
      <img src="images/image-equilibrium.jpg" alt="">
    </div>

    EDIT: OP wants to center it both vertically and horizontally.
    If you want to do that, you need to modify the most top parent as well (the <body> tag) and make its height 100%, like this:

    body {
      height: 100vh;
      margin: 0;
    }
    
    .parent {
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .card {
      width: 200px;
      height: 200px;
      background-color: black;
    }
    <div class="parent">
      <div class="card">
        <img src="images/image-equilibrium.jpg" alt="">
      </div>
    </div>
    Login or Signup to reply.
  2. The properties justify-content and align-items were applied for the children of .card. If you want to center the .card you will have to set the display property to flex for the parent of .card. or if the .card has a fixed width which in your case it has, you can also set the margin-x:auto on the .card, by doing so it will be aligned at the center of it’s parent container. Hope I was able to make you understand.

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