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

前端 未结 8 677
萌比男神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:41

    Assuming the element which is floated and will be centered is a div with an id="content" ...

    <body>
    <div id="wrap">
       <div id="content">
       This will be centered
       </div>
    </div>
    </body>
    

    And apply the following CSS:

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

    Here is a good reference regarding that.

    0 讨论(0)
  • 2020-12-02 07:49

    This works better when the id = container (which is the outer div) and id = contained (which is the inner div). The problem with the highly recommended solution is that it results in some cases into an horizontal scrolling bar when the browser is trying to cater for the left: -50% attribute. There is a good reference for this solution

            #container {
                text-align: center;
            }
            #contained {
                text-align: left;
                display: inline-block;
            }
    
    0 讨论(0)
提交回复
热议问题