Qwertie
Qwertie

Reputation: 6573

Use flexbox to center content while not making elements side by side

I am using flexbox to center content with justify-content: center which works as intended but flexbox also moves divs to be side by side which I don't want.

Here is an example

.flex {
  display: flex;
  justify-content: center;
}

.content {
  width: 100px;
  height: 100px;
  background-color: #000;
  margin: 10px;
}
<div class="flex">
  <div class="content">
  </div>
  <div class="content">
  </div>
</div>

How can I use flexbox while retaining the default one div on top of the other positioning.

Upvotes: 1

Views: 58

Answers (2)

Santhoshkumar
Santhoshkumar

Reputation: 780

Try following code,

.flex {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
}

.content {
  width: 100px;
  height: 100px;
  background-color: #000;
  margin: 10px;
}
<div class="flex">
  <div class="content">
  </div>
  <div class="content">
  </div>
</div>

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122145

You can set flex-direction: column and then you have to use align-items: center. Default flex-direction is row.

.flex {
  display: flex;
  align-items: center;
  flex-direction: column;
}

.content {
  width: 100px;
  height 100px;
  color: #000;
  border: 1px solid black;
  padding: 5px;
  margin: 5px;
}
<div class="flex">
  <div class="content"></div>
  <div class="content"></div>
</div>

Upvotes: 4

Related Questions