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:
2
Answers
Use the flexbox on the parent, not on the div you want to center:
If you want to keep the HTML structure (not inserting parent), you could just use the horizontal margin auto like this:
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:The properties
justify-content
andalign-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 themargin-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.