How to use safe center with flexbox?

后端 未结 2 1211
轮回少年
轮回少年 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

提交回复
热议问题