How do I center floated elements?

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

    Removing floats, and using inline-block may fix your problems:

     .pagination a {
    -    display: block;
    +    display: inline-block;
         width: 30px;
         height: 30px;
    -    float: left;
         margin-left: 3px;
         background: url(/images/structure/pagination-button.png);
     }
    

    (remove the lines starting with - and add the lines starting with +.)

    .pagination {
      text-align: center;
    }
    .pagination a {
      + display: inline-block;
      width: 30px;
      height: 30px;
      margin-left: 3px;
      background: url(/images/structure/pagination-button.png);
    }
    .pagination a.last {
      width: 90px;
      background: url(/images/structure/pagination-button-last.png);
    }
    .pagination a.first {
      width: 60px;
      background: url(/images/structure/pagination-button-first.png);
    }
    
    

    inline-block works cross-browser, even on IE6 as long as the element is originally an inline element.

    Quote from quirksmode:

    An inline block is placed inline (ie. on the same line as adjacent content), but it behaves as a block.

    this often can effectively replace floats:

    The real use of this value is when you want to give an inline element a width. In some circumstances some browsers don't allow a width on a real inline element, but if you switch to display: inline-block you are allowed to set a width.” ( http://www.quirksmode.org/css/display.html#inlineblock ).

    From the W3C spec:

    [inline-block] causes an element to generate an inline-level block container. The inside of an inline-block is formatted as a block box, and the element itself is formatted as an atomic inline-level box.

提交回复
热议问题