Aligning elements left and center with flexbox

前端 未结 7 468
眼角桃花
眼角桃花 2020-11-29 01:12

I\'m using flexbox to align my child elements. What I\'d like to do is center one element and leave the other aligned to the very left. Normally I would just set the left el

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 01:54

    EDIT: See Solo's answer below, it is the better solution.


    The idea behind flexbox is to provide a framework for easily aligning elements with variable dimensions within a container. As such, it makes little sense to provide a layout where the width of one element is totally ignored. In essence, that is exactly what absolute positioning is for, as it takes the element out of the normal flow.

    As far as I know, there is no nice way of doing this without using position: absolute;, so I would suggest using it... but If you REALLY don't want to, or can't use absolute positioning then I suppose you could use one of the following workarounds.


    If you know the exact width of the "Left" div, then you could change justify-content to flex-start (left) and then align the "Center" div like this:

    #center {
        position: relative;
        margin: auto;
        left: -{half width of left div}px;
    }
    

    If you do not know the width, then you could duplicate "Left" on the right side, use justify-content: space-between;, and hide the new right element: Just to be clear, this is really, really ugly... better to use absolute positioning than to duplicate content. :-)

    #parent {
      align-items: center;
      border: 1px solid black;
      display: flex;
      justify-content: space-between;
      margin: 0 auto;
      width: 500px;
    }
    #right {
        opacity: 0;
    }
    Left Center Left

提交回复
热议问题