how to evenly distribute elements in a div next to each other?

后端 未结 9 1146
有刺的猬
有刺的猬 2020-12-02 07:26

This is meant for a menu.
For example I have a div element with 3 spans in it, all of which have some margin, max-width and float (left or right).
It is positioned s

9条回答
  •  死守一世寂寞
    2020-12-02 07:49

    In the 'old days' you'd use a table and your menu items would be evenly spaced without having to explicitly state the width for the number of items.

    If it wasn't for IE 6 and 7 (if that is of concern) then you can do the same in CSS.

    Span 1 Span 2 Span 3

    CSS:

    div.demo {
        display: table;
        width: 100%;
        table-layout: fixed;    /* For cells of equal size */
    }
    div.demo span {
        display: table-cell;
        text-align: center;
    }
    

    Without having to adjust for the number of items.

    Example without table-layout:fixed - the cells are evenly distributed across the full width, but they are not necessarily of equal size since their width is determined by their contents.

    • http://jsfiddle.net/w3dx/ULQwf/

    Example with table-layout:fixed - the cells are of equal size, regardless of their contents. (Thanks to @DavidHerse in comments for this addition.)

    • http://jsfiddle.net/kqHWM/

    If you want the first and last menu elements to be left and right justified, then you can add the following CSS:

    div.demo span:first-child {
        text-align: left;
    }
    div.demo span:last-child {
        text-align: right;
    }
    

提交回复
热议问题