How do I center floated elements?

前端 未结 12 2809
谎友^
谎友^ 2020-11-22 00:16

I\'m implementing pagination, and it needs to be centered. The problem is that the links need to be displayed as block, so they need to be floated. But then, text-alig

12条回答
  •  忘掉有多难
    2020-11-22 00:57

    Since many years I use an old trick I learned in some blog, I'm sorry i don't remember the name to give him credits.

    Anyway to center floating elements this should work:

    You need a structure like this:

        .main-container {
          float: left;
          position: relative;
          left: 50%;
        }
        .fixer-container {
          float: left;
          position: relative;
          left: -50%;
        }
    • Floated element
    • Floated element
    • Floated element

    the trick is giving float left to make the containers change the width depending on the content. Than is a matter of position:relative and left 50% and -50% on the two containers.

    The good thing is that this is cross browser and should work from IE7+.

提交回复
热议问题