Distribute elements evenly using CSS

后端 未结 13 752
一生所求
一生所求 2020-12-09 02:55

A method to distribute elements evenly in a container using CSS appeared on Smashing Magazine today.

I recently had to use Javascript to achieve the same effect for

相关标签:
13条回答
  • 2020-12-09 03:24

    The top answer didn't work for me, and GarciaWebDev's answer won't do it for me yet because I need to support a few other browsers, including IE8.

    This method worked for me. The idea is to make a containing element text-align: justify and to make the elements to distribute display: inline-block.

    HTML:

    <div id="menu">
        <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/news">News</a></li>
            <li><a href="/theme">Theme</a></li>
            <li><a href="/activities">Activities</a></li>
            <li><a href="/contact">Contact</a></li>
            <li class="filler"></li>
        </ul>
    </div>
    

    CSS:

    #menu {
        text-align: justify;
    }
    
    ul {
        margin: 0;
        padding: 0;
    }
    
    #menu li {
        display: inline-block;
    }
    
    .filler {
        width: 100%;
        height: 0;
    }
    
    0 讨论(0)
  • 2020-12-09 03:26

    Yes, you can do it, as long as the widths of the elements to be distributed are known in advance. But it's a bit messy.

    The trick is, you want a spacing between each element of ‘(Wp-sum(Wc))/(Nc-1)’, that is width of the parent element minus the total width of all the child elements, divided equally between the number of gaps between the elements.

    Because CSS doesn't have the ability to do expressions, we have to hack it a bit. First we add a margin to the parent element of the size ‘sum(Wc)’, the total width of all child elements. So now the parent has width ‘(Wp-sum(Wc))’, and we can use a padding value in % relative to that width.

    So for example, for four images of sizes 10px, 20px, 40px and 80px respectively, our ‘sum(Wc)’ is 150px. Set that as the parent margin, then the children can have one-third of that width as padding between them.

    <style type="text/css">
        #nava { width: 10px; height: 20px;}
        #navb { width: 20px; height: 20px;}
        #navc { width: 40px; height: 20px;}
        #navd { width: 80px; height: 20px;}
    
        #nav { margin-right: 150px; white-space: nowrap; }
        #nava, #navb, #navc { padding-right: 33.3%; }
    </style>
    
    <div id="nav"
        ><img id="nava" src="nava.png" alt="a"
        ><img id="navb" src="navb.png" alt="b"
        ><img id="navc" src="navc.png" alt="c"
        ><img id="navd" src="navd.png" alt="d"
    ></div>
    

    The funny tag indentation is to avoid there being any whitespace between images. ‘nowrap’ is necessary because with the parent width set narrower than the page width, it wouldn't otherwise be possible to fit all the elements on the row. Finally, in IE you may need to add a wrapper div around the lot with ‘width: 100%; overflow: hidden’ to prevent unwanted scrollbars if you're spanning the whole page. And certainly you'll want to be in Standards Mode.

    This can work with textual elements too, if you make them inline blocks so you can add padding, and you size them explicitly in ems. It won't work if the sizes of the child elements are not known in advance (eg. they contain dynamic content), as you won't know the ‘sum(Wc)’ value to use.

    To be honest I would probably just use a table. The table layout algorithm copes very smoothly with calculating how to distribute spare table width. (Use ‘table-layout: fixed’ for best results with known-width cells, or ‘auto’ to respond to dynamic contents.) This way you also don't have to worry about pixel rounding errors.

    0 讨论(0)
  • 2020-12-09 03:29

    Thanks to the CSS3 Flexbox module, this is possible with two lines of CSS.

    Check the Browser compatibility table for Flexbox

    HTML

    <div id="menu">
      <ul>
        <li><a href="/">Home</a>
        </li>
        <li><a href="/news">News</a>
        </li>
        <li><a href="/theme">Theme</a>
        </li>
        <li><a href="/activities">Activities</a>
        </li>
        <li><a href="/contact">Contact</a>
        </li>
      </ul>
    </div>
    

    CSS

    ul {
      display: flex;
    }
    li {
      flex: 1; /* Short hand for flex-grow: 1 and flex-shrink: 1 */
    }
    

    Output:

    ul, li {
      margin: 0;
      padding: 0;
    }
    ul {
      display: flex;
      list-style: none;
    }
    li {
      flex: 1;
      text-align: center;
    }
    <div id="menu">
      <ul>
        <li><a href="/">Home</a>
        </li>
        <li><a href="/news">News</a>
        </li>
        <li><a href="/theme">Theme</a>
        </li>
        <li><a href="/activities">Activities</a>
        </li>
        <li><a href="/contact">Contact</a>
        </li>
      </ul>
    </div>

    0 讨论(0)
  • 2020-12-09 03:30

    Even though Colin Brogan's answer provides solid foundation to approach a "almost there" resolution to the problem, it still depends on text length. If text is too long, the "cell" will be wider and thus have more space on the left. I tried to address the problem based on the code presented in his answer, but I concluded that the problem has not a real possible solution with tables or fake-tables (display:table-cell).

    So we'll have to wait for CSS3 flexible box model to be more widely supported (you can check updated support here). In the meantime, you can use the Flexie polyfill to patch browsers that don't support it. If you want to check how it'll look like on WebKit now (without needing polyfill), you can try the following CSS:

    #menu ul {
      display: -webkit-box;
      -webkit-box-orient: horizontal;
      -webkit-box-pack: justify;
      width: 940px;
      list-style: none;
      padding: 0;
      border: 1px solid gray;
    }
    #menu li {
      border: 1px solid silver;
    }
    

    Notice it only uses WebKit prefixes. You should add prefixes for the other browsers aswell if you decide to take it to production website.

    This approach does accept an unknown amount of items and text-widths, without any knowledge of their actual widths, and distribute them evenly across their container (in this case, #menu ul).

    If you decide to be conservative, the approach suggested by Colin Brogan is the most acceptable given that you keep your texts on the same approximately length. If not, wider spaces will start to show.

    0 讨论(0)
  • 2020-12-09 03:33

    Here is the code in jQuery format for anyone who finds it useful

    function justifyClients() {
                            var menuItems  = $("#clients-wrapper ul li").get();                         
                            var menuWidth  = $("#clients-wrapper ul").width();                          
                            var totalWidth = 0;
    
                            $("#clients-wrapper ul li").each(function(i,e)
                                            {
                                                totalWidth += $(e).width();
                                            });
    
                            var margin = (menuWidth - 4 - totalWidth) / ($("#clients-wrapper ul li").length - 1);
                            margin = parseInt(margin);
    
                            $("#clients-wrapper ul li").each(function(i,e) {
    
                                if(i < $("#clients-wrapper ul li").length - 1)
                                {
                                    alert(i + " " + $("#clients-wrapper ul li").length);
                                    $(e).css('margin-right',  margin);
                                }
                            });
                        }
    
                        $(document).ready(function() {
                          justifyClients();
                        });
    
    0 讨论(0)
  • 2020-12-09 03:39

    If you were using text-based sizes (em, ex) it'd be a lot easier. You can then deal in letters rather than pixels.

    Example: The whole thing is 30 capital letter Ms wide. You can then use the width of each nav element (based on its textual content) and do your math statically from there.

    0 讨论(0)
提交回复
热议问题