How to horizontally center a floating element of a variable width?

前端 未结 8 678
萌比男神i
萌比男神i 2020-12-02 06:51

How to horizontally center a floating element of a variable width?

Edit: I already have this working using a containing div for the floating element and

8条回答
  •  天命终不由人
    2020-12-02 07:28

    The popular answer here does work sometimes, but other times it creates horizontal scroll bars that are tough to deal with - especially when dealing with wide horizontal navigations and large pull down menus. Here is an even lighter-weight version that helps avoid those edge cases:

    #wrap {
        float: right;
        position: relative;
        left: -50%;
    }
    #content {
        left: 50%;
        position: relative;
    }
    

    Proof that it is working!

    To more specifically answer your question, it is probably not possible to do without setting up some containing element, however it is very possible to do without specifying a width value. Hope that saves someone out there some headaches!

提交回复
热议问题