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

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

    Say you have a DIV you want centred horizontally:

     
    Lorem ipsum

    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.

提交回复
热议问题