Flexbox auto margins don't work with justify

I have a table where a cell can contain a number of icons, as well as text. If icons are present, they appear to the left of the text. There are a couple of possible alignment cases:

  • Only an icon is present: The icon should be centered
  • Only text is present: The text should be left aligned
  • Both icons and text are present: Both the icon and text should be left aligned
  • I thought that I could accomplish this and other more complicated alignments by wrapping everything within the table-cell with a flexbox, using justify-content: center; , and then applying margin-right: auto; to the text div.

    If there is text, the auto margin will push everything over to the left.

    If not, the justify-content style will center the icons.

    Here is a codepen containing my approach.

    .flexbox {
      display: flex;
      flex-direction: row;
      justify-content: center;
      border: 2px solid black;
      width: 300px;
      height: 17px;
    }
    .icon {
      height: 17px;
      width: 17px;
      background-color: red;
    }
    .text {
      margin-right: auto;
    }
    <div class="flexbox">
      <div class="icon"></div>
      <div class="text">asdf</div>
    </div>

    As stated in the flexbox specification:

    Prior to alignment via justify-content and align-self , any positive free space is distributed to auto margins in that dimension.

    In other words, auto margins have precedence over justify-content .

    In your example, Chrome appears to be in compliance with the spec. (Firefox, as well.)

    But IE11 – in cases where the parent has justify-content – is ignoring margin-right: auto on the flex item. This appears to be a bug.

    When justify-content is removed, auto margins work.

    One workaround would be to remove justify-content entirely and rely solely on auto margins:

  • Only an icon is present: The icon should be centered
  • .icon { margin: 0 auto; }
    

    .flexbox {
      display: flex;
      flex-direction: row;
      border: 2px solid black;
      width: 300px;
      height: 17px;
    }
    .icon {
      height: 17px;
      width: 17px;
      background-color: red;
    }
    .icon {
      margin: 0 auto;
    }
    <div class="flexbox">
      <div class="icon"></div>
    </div>

    This work around of removing justify-content doesn't work for me. If you look at this example in IE11 you will see: Codepen example

    .wrapper {
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto;
        width: 200px;
        height: 200px;
        background-color: white;
    }
    
    .item {
        margin: auto;
        width: 50px;
        height: 50px;
        background-color: red;
    }
    
    链接地址: http://www.djcxy.com/p/76038.html

    上一篇: flexbox对齐项目混乱

    下一篇: FlexCit自动边距不适用于对齐