Align items to left, and container to center

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!


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>

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/

链接地址: http://www.djcxy.com/p/76050.html

上一篇: CSS Flexbox:左边的中心容器

下一篇: 将项目对齐到左侧,将容器对齐到中间