How do I center floated elements?

前端 未结 12 2742
谎友^
谎友^ 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 01:01

    Centering floats is easy. Just use the style for container:

    .pagination{ display: table; margin: 0 auto; }
    

    change the margin for floating elements:

    .pagination a{ margin: 0 2px; }
    

    or

    .pagination a{ margin-left: 3px; }
    .pagination a.first{ margin-left: 0; } 
    

    and leave the rest as it is.

    It's the best solution for me to display things like menus or pagination.

    Strengths:

    • cross-browser for any elements (blocks, list-items etc.)

    • simplicity

    Weaknesses:

    • it works only when all floating elements are in one line (which is usually ok for menus but not for galleries).

    @arnaud576875 Using inline-block elements will work great (cross-browser) in this case as pagination contains just anchors (inline), no list-items or divs:

    Strengths:

    • works for multiline items.

    Weknesses:

    • gaps between inline-block elements - it works the same way as a space between words. It may cause some troubles calculating the width of the container and styling margins. Gaps width isn't constant but it's browser specific (4-5px). To get rid of this gaps I would add to arnaud576875 code (not fully tested):

      .pagination{ word-spacing: -1em; }

      .pagination a{ word-spacing: .1em; }

    • it won't work in IE6/7 on block and list-items elements

提交回复
热议问题