将容器中的Flexbox项目居中,如果左侧已有项目

这个问题在这里已经有了答案:

  • 中心和右对齐flexbox元素2答案

  • 你希望在父块中居中嵌套,这样一个块将不会被计数,所以你需要将它从流中取出,并将其position: absolute 。 在那里你可以阅读更多。


    我会这样做:

    <div>
      <a class="a">&rarr;</a>
      <a class="b">here <br> is a load of text.<br>I want it to be centered in the div,<br>not shifted to the right</a>
    </div>
    
     div {
      position relative;
      display: flex; 
      justify-content: center;
      align-items: center; 
      max-width: 22em; 
      height: 22em;
      border:1px solid blue; 
    
      a.a {
        position: absolute;
        left: 0;
        align-self: center;
      }
    
      a.b {
        display: flex;
        justify-content: center;
        align-self: center;
        flex: 1;
      }
    }
    

    https://jsfiddle.net/km5gdrcm/2/


    将图标置于绝对位置,这会将其从文档流中移出,以免影响居中框。

    <div class="container">
    <a class="icon">&rarr;</a>
    <a class="centered-box">here <br> is a load of text.<br>I want it to be centered in the div,<br>not shifted to the right</a>
    </div>
    
    .centered-box {
      flex: 1;
    }
    
    .container {
      position: relative;
      display: flex; 
      width: 20em; 
      align-items: center; 
      border:1px solid blue; 
      text-align:center;
    }
    
    .icon {
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
    }
    

    小提琴:https://jsfiddle.net/nt4shjn5/

    小提琴添加到容器,以避免溢出图标上的文字:https://jsfiddle.net/nt4shjn5/1/

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

    上一篇: Center a flexbox item in the container, if there is already an item to the left

    下一篇: Horizontal centering of 3 flexbox items of the same width