Center and right align flexbox elements

I would like to have A B and C aligned in the middle.

How can I get D to go completely to the right?

BEFORE:

AFTER:

What's the best practice for doing this?

ul {
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
li {
  display: flex;
  margin: 1px;
  padding: 5px;
  background: #aaa;
}
li:last-child {
  background: #ddd;
  /* magic to throw to the right*/
}
<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
</ul>

Below are five options for achieving this layout:

  • CSS Positioning
  • Flexbox with Invisible DOM Element
  • Flexbox with Invisible Pseudo-Element
  • Flexbox with flex: 1
  • CSS Grid Layout

  • Method #1: CSS Positioning Properties

    Apply position: relative to the flex container.

    Apply position: absolute to item D.

    Now this item is absolutely positioned within the flex container.

    More specifically, item D is removed from the document flow but stays within the bounds of the nearest positioned ancestor.

    Use the CSS offset properties top and right to move this element into position.

    li:last-child {
      position: absolute;
      top: 0;
      right: 0;
      background: #ddd;
    }
    ul {
      position: relative;
      padding: 0;
      margin: 0;
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
    }
    li {
      display: flex;
      margin: 1px;
      padding: 5px;
      background: #aaa;
    }
    p {
      text-align: center;
      margin-top: 0;
    }
    span {
      background-color: aqua;
    }
    <ul>
      <li>A</li>
      <li>B</li>
      <li>C</li>
      <li>D</li>
    </ul>
    <p><span>true center</span></p>

    Very clear question. I couldn't help but post the answer after a few hours of digging. We Could of solved this with tables, table-cell, absolute positions, transforms but we just had to do it with flexbox :)

    .parent {
      display: flex;
      justify-content: flex-end;
    }
    
    .center {
      margin: auto;
    }
    

    http://codepen.io/rgfx/pen/BLorgd

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

    上一篇: 我能否阻止100%宽度文本框超出其容器范围?

    下一篇: 居中并右对齐Flexbox元素