2

Is it possible to use display: flex; to align all items to the left (flex-wrap: wrap; align-items: flex-start; justify-content: flex-start;) but the container it self to the center (like margin: 0 auto;)?

It seems like flex-containers are always scaled to 100% width, why the automatic margin won't work. Does anybody have an idea how to achieve what I try?

.container {
    width: auto;
    margin: 0 auto;
    display: -webkit-flex;
    display: -moz-flex;
    display: -ms-flexbox; // IE10 uses -ms-flexbox
    display: -ms-flex; // IE11
    display: flex;
    -webkit-flex-wrap: wrap;
    -moz-flex-wrap: wrap;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    -webkit-justify-content: flex-start;
    -moz-justify-content: flex-start;
    -ms-justify-content: flex-start;
    justify-content: flex-start;
    -webkit-align-items: flex-start;
    -moz-align-items: flex-start;
    -ms-align-items: flex-start;
    align-items: flex-start;
}
.item {
    display: block;
    width: 220px;
}

EDIT: Important! While the container has an auto width!

SoBiT
  • 408
  • 5
  • 18
  • 1
    Please post your code. – Gerrit Bertier Nov 17 '15 at 16:08
  • 1
    Something like this? http://jsfiddle.net/smaye81/hvtz1j1s/ – sma Nov 17 '15 at 16:10
  • Well, now we know, that flex allows us to set the width of the container. Unfortunately I'd like to have an auto width (according to the items inside the flexbox). But thank you anyway – SoBiT Nov 17 '15 at 16:13
  • Possible duplicate of [Center flex container but align left flex items](http://stackoverflow.com/questions/32802202/center-flex-container-but-align-left-flex-items) – Michael Benjamin Nov 17 '15 at 16:49

2 Answers2

3

Yes, using text-align:center on a parent (or body) and display:inline-flex instead of display:flex.

This operates much the same as the difference between display:inline-block and display:block.

MDN says:

The element behaves like an inline element and lays out its content according to the flexbox model.

body {
  background: #eee;
  text-align: center;
}
.inner {
  display: inline-flex;
  width: auto;
  /* stated but not required */
  background: #ccc;
  padding: 15px;
}
p {
  padding: 15px;
  border: 1px solid red;
}
<div class="inner">
  <p>1</p>
  <p>2</p>
  <p>3</p>
</div>
Paulie_D
  • 107,962
  • 13
  • 142
  • 161
  • You can keep the outer as `display: flex` by using `justify-content: center`, this way you can use all the other flex properties to modify the inner(s) and you could keep the inner as flex as well. – kmiyashiro Nov 17 '15 at 16:22
-1

For the parent, you can use display: inline-flex , which has the same effect as display: inline-block compared to display: block. The flex won't claim the whole page width anymore. You can find more information about flex here: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

xbilek18
  • 93
  • 1
  • 11