How to use safe center with flexbox?

后端 未结 2 1135
轮回少年
轮回少年 2020-11-30 13:55

Centred flexbox items can have undesirable behaviour when they overflow their container.

Several non-flex solutions have been provided for this issue, but according

相关标签:
2条回答
  • 2020-11-30 14:21

    safe isn't implemented in most browsers yet. You can recreate some of its functionality with auto margins.

    I was trying to use justify-content: safe center to have a bunch of items centered in a footer when the viewport was wide, but have them able to scroll without clipping off the left side when the viewport was small.

    When I tried to fix this with auto margins as Ason suggested, it did fix the clipping, but it also spread the items out evenly, which isn't what I wanted.

    I found I could simulate safe center in this context by applying auto margins to only the first and last elements.

    Assuming my flex items have class "item":

    .item:first-child {
        margin-left: auto;
    }
    .item:last-child {
        margin-right: auto;
    }
    

    CodePen with examples comparing each solution

    0 讨论(0)
  • 2020-11-30 14:39

    The safe keyword is still a working draft, and not many (if any) browsers support it yet, so to get the same effect, cross browser, use auto margins for now, which should be set on the flex item.

    Updated codepen

    Note, to compensate for the modal's 50px top/bottom margin, use padding on modal-container.

    .modal-container
    {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: flex-start;                /*  changed  */
      position: fixed;
      width: 100vw;
      height: 100vh;
      overflow-y: scroll;
      padding: 50px 0;                        /*  added  */
      box-sizing: border-box;                 /*  added  */
    }
    .modal-container > #modal
    {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin: auto 0;                         /*  changed  */
      padding: 12px;
      width: 50%;
      background-color: #333;
      cursor: pointer;
    }
    
    0 讨论(0)
提交回复
热议问题