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

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

    Can't you just use display: inline block and align to center?

    Example.

    0 讨论(0)
  • 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!

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

    for 50% element

    width: 50%;
    display: block;
    float: right;
    margin-right: 25%;
    
    0 讨论(0)
  • 2020-12-02 07:30
    .center {
      display: table;
      margin: auto;
    }
    
    0 讨论(0)
  • 2020-12-02 07:35

    Say you have a DIV you want centred horizontally:

     <div id="foo">Lorem ipsum</div>
    

    In the CSS you'd style it with this:

    #foo
    {
      margin:0 auto; 
      width:30%;
    }
    

    Which states that you have a top and bottom margin of zero pixels, and on either left or right, automatically work out how much is needed to be even.

    Doesn't really matter what you put in for the width, as long as it's there and isn't 100%. Otherwise you wouldn't be setting the centre on anything.

    But if you float it, left or right, then the bets are off since that pulls it out of the normal flow of elements on the page and the auto margin setting won't work.

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

    You can use fit-content value for width.

    #wrap {
      width: -moz-fit-content;
      width: -webkit-fit-content;
      width: fit-content;
      margin: auto;   
    }
    

    Note: It works only in latest browsers.

    0 讨论(0)
提交回复
热议问题