Unknown width for variable number of columns
P粉441076405
P粉441076405 2023-08-20 21:40:19
0
1
602
<p>I want to arrange some items in a column. I can't predict the width or height of the item, nor the width or height of the container. I also can't predict how many columns will fit or what the width of the columns should be. I want the browser to arrange the items in the maximum number of columns without exceeding the width of the container, while minimizing the height of the container. </p> <p>This solved the problem, but is there a better way? Can this be achieved without using jQuery? Can it be done in a way that older browsers will display it properly (perhaps by arranging it in rows instead of columns)? </p> <pre class="brush:php;toolbar:false;"><style> #wrapper { column-width: 100px; /* jQuery will change this value */ padding: 20px; border: 2px solid blue; } .item { padding: 50px; border: 2px solid green; } </style> <div id="wrapper"> <div class="item">1</div> <div class="item">2</div> <div class="item">3</div> <div class="item">4</div> <div class="item">5</div> <div class="item">6</div> <div class="item">7</div> <div class="item">8</div> <div class="item">9</div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> // Get the maximum width of child elements. var maxWidth = 0; jQuery('#wrapper .item').each(function() { var width = jQuery(this).outerWidth(true); if (width > maxWidth) { maxWidth = width; } }); // Set the wrapper's column width to the maximum width. jQuery('#wrapper').css('column-width', maxWidth 'px'); </script></pre> <p><br /></p>
P粉441076405
P粉441076405

reply all(1)
P粉865900994

You can use a grid to achieve this

#wrapper {
    display: grid;
    grid-auto-flow: row;
    grid-gap: 20px;
    grid-template-columns: repeat(9, 1fr);   //将9更改为列数
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template