wizardzeb
wizardzeb

Reputation: 1596

Center siblings in flexbox

This is my current html

<body>
    <div class="header"></div>
    <div class="side"></div>
    <div class="stuff"></div>
    <div class="footer"></div>
</body>

Is there anyway I could snap the sibling divs to the center, as if they were in a wrapper div? That way no matter what happened they would be side by side and in the center. I unfortunately having a hard time because I have other things in the parent div.

Something like this.

Is there any way I can do this using flexbox? and without adding html?

Upvotes: 1

Views: 238

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 372264

body {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;          /* 1 */
  align-content: space-between;     /* 2 */
  height: 100vh;
  margin: 0;
}

div {
  flex: 0 0 90%;                    /* 3 */
  height: 100px;
  border: 2px dashed red;
}

.side, .stuff {
  flex-basis: 25%;                 /* 4 */
  margin: 5px;
}
<div class="header">header</div>
<div class="side">stuff</div>
<div class="stuff">side</div>
<div class="footer">footer</div>

jsFiddle demo

Notes:

  1. Flex items on every line are centered horizontally.
  2. First line pins to top. Bottom line pins to bottom. Middle line is vertically centered.
  3. Force one line per row.
  4. Override (3), so two items can display on the second line.

Upvotes: 2

Related Questions